问题
I have a PivotTable that comes from the following table:
+---------+---+-----+
| A | B | C |
+-+---------+---+-----+
|1| Date |Id |Value|
+-+---------+---+-----+
|2|4/01/2013|1 |4 |
+-+---------+---+-----+
|3|4/01/2013|2 |5 |
+-+---------+---+-----+
|4|4/01/2013|1 |20 |
+-+---------+---+-----+
|5|4/02/2013|2 |20 |
+-+---------+---+-----+
|6|4/02/2013|1 |15 |
+-+---------+---+-----+
And I want to aggregate first by Id and then by Date, using Max to aggregate by Id and then Sum to aggregate by Date. The resulting table would look like this:
+---------+----------------+
| A | B |
+-+---------+----------------+
|1| Date |Sum(Max(Id,Date)|
+-+---------+----------------+
|2|4/01/2013|25 |
+-+---------+----------------+
|3|4/02/2013|35 |
+-+---------+----------------+
The 25 above comes from getting the Max per Id per Date (Max(1, 4/01/2013) -> 20 and Max(2, 4/01/2013) -> 5, so the Sum of those Max is 25.
I can do the two levels of aggregation easily by adding the Date and Id columns into the Rows section of the PivotTable, but when choosing an aggregation function for Value, I can either choose Max, getting a Max of Max, or Sum, getting a Sum of Sum. That is, I cannot get a Sum of Max.
Do you know how to achieve this? Ideally, the solution would not be to compute a PivotTable and then copy from there or get a formula, because that would break easily if I want to dynamically change fields.
Thanks!
回答1:
This is how I would do it in SQL:
SELECT DATE, SUM(MAXED_VAL) as SummedMaxedVal
FROM (
SELECT DATE, ID, MAX(VALUE) as MAXED_VAL
FROM table
GROUP BY DATE, ID
)
GROUP BY DATE
来源:https://stackoverflow.com/questions/21563086/sum-of-max-in-pivottable-for-excel