1

我有一张这样的桌子:

id   person_id  total amount    date_time
1    101        2000            2001-12-10
2    102        1000            2001-12-10
3    102        3000            2001-12-10
4    102        2000            2001-12-10
5    103        1000            2001-12-11
6    101        1000            2001-12-11
7    102        3000            2001-12-11
8    102        4000            2001-12-11
9    102        4000            2001-12-11

我希望输出类似于以下日期 2001-12-11

person_101   person_102   person_103
1000         11000         1000

我尝试过使用该函数,但被and子句SUM()卡住了。我该如何解决这个问题?WHEREJOIN

4

2 回答 2

2
SELECT
  SUM(CASE WHEN person_id = 101 THEN total_amount ELSE 0 END) as person_101,
  SUM(CASE WHEN person_id = 102 THEN total_amount ELSE 0 END) as person_102,
  SUM(CASE WHEN person_id = 103 THEN total_amount ELSE 0 END) as person_103
FROM
  my_table
WHERE
  date_time ='2001-12-11'
于 2013-06-05T07:07:07.277 回答
0

您需要旋转数据,不幸的是这不是动态的mysql,试试这个:

SELECT
    SUM(IF(person_id = 101,total_amount,0)) as person_101,
    SUM(IF(person_id = 102,total_amount,0)) as person_102,
    SUM(IF(person_id = 103,total_amount,0)) as person_103
FROM
    my_table
WHERE
    date_time = '2001-12-11'

您也可以按日期进行透视拆分,只需将其放在字段列表中并按其分组:

SELECT
    date_time,
    SUM(IF(person_id = 101,total_amount,0)) as person_101,
    SUM(IF(person_id = 102,total_amount,0)) as person_102,
    SUM(IF(person_id = 103,total_amount,0)) as person_103
FROM
    my_table
GROUP BY
    date_time
于 2013-06-05T07:04:54.283 回答