MYSQL PIVOT从两个表中选择数据

时间:2017-06-09 09:21:03

标签: mysql sql

我在这里遇到一些问题,我有两张桌子

1st Table: user
[user_id,name]
(1,"Shelby")
(2,"barray")
(3,"Obor")

2nd Table: payment_transaction
[payment_id,payment_date,payment_user_id (this refer to user id from table user), payment_amount]
(1,"2017-06-09 16:48:37",1,20)

我想像这个透视示例一样输出它:

name | Jan | Feb | Mar | Apr | May | June | July .. Dec | <br>
Shelby | 0 | 0 | 0 | 0 | 0 | 20 | ... 0 |<br>
barray | 0 | 0 | 0 | 0 | 0 | 0 | ... 0 |<br>
Obor   | 0 | 0 | 0 | 0 | 0 | 0  | ... 0 |<br>

我设法正确使用这个sql:

    SELECT pt.name,
SUM(case when month(s.payment_date) = 1 THEN s.payment_amount ELSE 0 END) 
'Jan',
SUM(case when month(s.payment_date) = 2 THEN s.payment_amount ELSE 0 END) 
'Feb',
SUM(case when month(s.payment_date) = 3 THEN s.payment_amount ELSE 0 END) 
'Mar',
SUM(case when month(s.payment_date) = 4 THEN s.payment_amount ELSE 0 END) 
'Apr',
SUM(case when month(s.payment_date) = 5 THEN s.payment_amount ELSE 0 END) 
'May',
SUM(case when month(s.payment_date) = 6 THEN s.payment_amount ELSE 0 END) 
'Jun',
SUM(case when month(s.payment_date) = 7 THEN s.payment_amount ELSE 0 END) 
'Jul',
SUM(case when month(s.payment_date) = 8 THEN s.payment_amount ELSE 0 END) 
'Aug',
SUM(case when month(s.payment_date) = 9 THEN s.payment_amount ELSE 0 END) 
'Sep',
SUM(case when month(s.payment_date) = 10 THEN s.payment_amount ELSE 0 END) 
'Oct',
SUM(case when month(s.payment_date) = 11 THEN s.payment_amount ELSE 0 END) 
'Nov',
SUM(case when month(s.payment_date) = 12 THEN s.payment_amount ELSE 0 END) 
'Dec'
from user pt left join payment_transactions on pt.user_id = s.payment_user_id group by pt.name

但是,我想尽快将Where子句用于在特定日期获取数据

    WHERE YEAR(s.payment_date)='2017'

它只输出:

name | Jan | Feb | Mar | Apr | May | June | July .. Dec | <br>
Shelby | 0 | 0 | 0 | 0 | 0 | 20 | ... 0 |<br>

另外两个名字没有出来。

我可能知道在一年中检索数据库的错误在哪里吗?

谢谢你!

0 个答案:

没有答案