问题
I have a table: (Edited with x5)
_date(2014-03-05;2014-04-05)
_period(1,2,3,4,5,1,2,3,4,5,1,2; 1,2,3,4,5,1,2,3,4,5)
_id(x1,x1,x1,x1,x1,x2,x2,x2,x2,x2,x3,x3;x4,x4,x4,x4,x4,x5,x5,x5,x5,x5)
_reading(1,1,1,1,1,2,2,2,2,2,5,6;1,1,1,1,1,2,1,1,1,1)
_reading2 (5,5,5,5,5,4,4,4,4,4,7,7;1,1,1,1,1,1,1,1,1,1)
image of the table 1
i need a result like below which eliminates all data which doesn't have full period 1 to 5 for the _id, then calculates the sum of _reading for a day and sum of _reading2 for each distinct _id for a day:
_date(2014-03-05;2014-04-05)
sum_reading(15;11)
sum_reading2 (9;2)
image of the table2
回答1:
Tested: SQL Fiddle
I use a subquery to eliminate the _IDs which don't have a full 5 periods. I then use the group by date and _ID and sum vs sum distinct to get the sum total vs summing distinct values.
SELECT A._date, sum(_Reading) as _Reading,
sum(Distinct _Reading2) as _Reading2
FROM table A
INNER JOIN (SELECT _ID, _date
FROM table
GROUP BY _ID, _date
HAVING count(_Period) = 5) B
on A._ID = B._ID
and A._Date = B._Date
GROUP BY A._Date
This still may not meet your needs because order of readings and a reduction may actually be important in reading 2; not just summing distinct. But as I'm unclear as to the requirements, and this matches the desired result... it's the best I can for now.
Update for X5 - By getting the sum in a distinct at the inner level we can then sum the readings which I think may address the issue.
SELECT A._date, sum(_Reading) as _Reading,
sum(B.I_reading2) as _Reading2
FROM table A
INNER JOIN (SELECT _ID, _date, Sum(Distinct _Reading2) as I_Reading2
FROM table
GROUP BY _ID, _date
HAVING count(_Period) = 5) B
on A._ID = B._ID
and A._Date = B._Date
GROUP BY A._Date
来源:https://stackoverflow.com/questions/38721292/mysql-sum-by-a-different-group-by