sql - sql中的分类
问题描述
我有两张桌子:
兴趣表:
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
解决方案
使用条件聚合
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
推荐阅读
- c++ - 递归反向索引 std::array
- django - 我在使用 Celery、Redis 和 Django 时遇到问题
- python - 如何从列表中选择特定的字典(没有键名)?
- flutter - 将图像添加到 RichText 元素
- css - 在材料设计组件中如何计算原色的浅色和深色版本?
- mongodb - 如何在MongoDB的项目数组中查找包含非空数组的文档
- mulesoft - 如何在 MuleSoft 中将分支合并为 master(Anypoint 设计中心)
- apache-nifi - NiFi:如何在所有节点中写入本地文件信息?
- web - Flutter For Web 有没有办法存储数据?
- java - 通过谷歌电子邮件地址登录