我的数据库中有记录,如下所示
userid email first_name SUM Currency_flag
1 abc@gmail.com User2 8609.00 0
1 abc@gmail.com User2 12.00 1
9 xyz@gmail.com User1 99.00 0
9 xyz@gmail.com User1 200.00 1
34 qwer@gmail.com User3 345.00 0
34 qwer@gmail.com User3 200.00 1
12 dfg@gmail.com User4 0.00 0
12 dfg@gmail.com User4 280.00 1
现在我想将它们显示如下
userid email first_name SUM_0 SUM_1
1 abc@gmail.com User2 8609.00 12.00
9 xyz@gmail.com User1 99.00 200.00
34 qwer@gmail.com User3 345.00 200.00
12 dfg@gmail.com User4 0.00 280.00
其中sum_0
是currency_flag=0
时的SUM值,而SUM_1
时currency_flag=1
是SUM值。
我该怎么做?
答案 0 :(得分:1)
试试这个:
SELECT
`userid`, `email`, `first_name`,
SUM(IF(`currency_flag`=0, `SUM`, 0)) AS `SUM_0`
SUM(IF(`currency_flag`=1, `SUM`, 0)) AS `SUM_1`
FROM `users`
GROUP BY (`userid`)
答案 1 :(得分:1)
这样做的一种方法是自我加入:
SELECT A.UserID, A.Email, A.First_Name, A.SUM AS SUM_0, B.SUM AS SUM_1
FROM (SELECT * FROM AnonymousTable WHERE Currency_Flag = 0) AS A
JOIN (SELECT UserID, SUM FROM AnonymousTable WHERE Currency_Flag = 1) AS B
ON A.UserID = B.UserID;
答案 2 :(得分:0)
select userid,email,first_name,sum(if(currency_flag=0,SUM,0)),sum(if(currency_flag=1,SUM,0))
from table
group by 1