Name | Amount | Date
_____________________
Jacob | 15 | 1-Oct-16
Jacob | 50 | 2-Oct-16
Ethan | 24 | 3-Oct-16
Jacob | 30 | 3-Oct-16
William | 17 | 1-Oct-16
William | 11 | 2-Oct-16
Ethan | 36 | 3-Oct-16
Ethan | 9 | 1-Oct-16
我有上面的表格,我想要最近5天的金额总和
Name | 5-oct-16 | 4-oct-16 | 3-oct-16 | 2-oct-16| 1-oct-16
___________________________________________________________
Jacob | 0 | 0 |30 | 50 | 15
Ethan | 0 | 0 |60 | 0 | 9
William | 0 | 0 |0 | 11 | 17
希望按名称分组,并将最后5天的金额总和分开。
答案 0 :(得分:3)
我认为你想要条件聚合:
SELECT Name,
SUM(CASE DATE WHEN '2016-10-05' THEN Amount ELSE 0 END) as amount_2016105,
SUM(CASE DATE WHEN '2016-10-04' THEN Amount ELSE 0 END) as amount_2016104,
SUM(CASE DATE WHEN '2016-10-03' THEN Amount ELSE 0 END) as amount_2016103,
SUM(CASE DATE WHEN '2016-10-02' THEN Amount ELSE 0 END) as amount_2016102,
SUM(CASE DATE WHEN '2016-10-01' THEN Amount ELSE 0 END) as amount_2016101
FROM MyTable
GROUP BY Name;