我正在尝试进行类似这样的查询...
id | id2 | profit | expense | status | date
1 1 10 20 Active 7-3-11
1 1 11 5 Not Act 7-4-11
1 2 5 10 Active 7-4-11
我希望按ID分组,Id2将利润和费用列相加,然后返回最新状态,就像这样。
id | id2 | profit | expense | status
1 1 22 25 Not Act
1 2 5 10 Active
到目前为止我所尝试的是缺少它应该具有的大部分数据,并且大多数时候id为null但并非总是如此。
SELECT * FROM
tbl
JOIN
(SELECT
id,
id2,
max(date) maxdate
FROM
tbl
GROUP BY
id,
id2) sub
ON tbl.id = sub.id AND
tbl.id2 = sub.id2 AND
tbl.date = sub.maxdate;
任何帮助都会很棒!
答案 0 :(得分:1)
SELECT
id,
id2,
sum(profit) profit,
sum(expense) expense,
(select status from tbl t1 where t1.id=tbl.id and t1.id2=tbl.id2 order by date desc limit 1)
FROM
tbl
GROUP BY
id,
id2