我有两个桌子:
兴趣表:
Date VisitorID Interest
5/3 A $30
5/4 C $15
5/7 B $21
访问者表:
VisitorID InterestSegment
A Simple
B Compound
C Simple
我需要查询2个表以按天显示“简单”和“复合”细分。解决方案应如下所示:
Date Total spend from Simple Total spend from Compound
5/3 $30 NULL
5/4 $15 NULL
5/7 NULL $21
我尝试使用以下代码,但未按我想要的方式进行分类。另外,我需要用$替换$,因为SUM函数在varchar字段上不起作用。
SELECT p.Date, m.InterestSegment, SUM(REPLACE(p.Interest,'$',''))
FROM visitor as m
LEFT JOIN interest as p ON m.VisitorID = p.VisitorID
GROUP BY Date, InterestSegment, Interest
答案 0 :(得分:0)
使用条件聚合
SELECT p.Date,
SUM(case when InterestSegment='Simple' then Interest else 0 end)
Total_spend_from_Simple,
SUM(case when InterestSegment='Compound' then Interest else 0 end)
Total_spend_from_Compound
FROM visitor as m
JOIN interest as p ON m.VisitorID = p.VisitorID
GROUP BY p.Date
答案 1 :(得分:0)
尝试这样的事情。
SELECT p.date,
SUM(CASE WHEN m.interestSegment = 'Simple' THEN p.interest END) "Total Spend From Simple",
SUM(CASE WHEN m.interestSegment = 'Compound' THEN p.interest END) "Total Spend From Compound"
FROM INTEREST p, VISITORS m
WHERE p.visitorId = m.visitorId
GROUP BY p.date