sql - 获取行数据的计数
问题描述
有一个表变量(这里我把它写成一个普通的表)
CREATE TABLE TEST (memberid int, producttype varchar(7))
这个表有几十万行,但是对于这个例子,我添加的少了很多
Insert into test values(1,'book')
Insert into test values(1,'clothes')
Insert into test values(2,'book')
Insert into test values(3,'book')
Insert into test values(4,'clothes')
Insert into test values(5,'book')
Insert into test values(5,'clothes')
Insert into test values(6,'book')
Insert into test values(7,'book')
我需要得到:
- 只有“书”的会员
- 只有“衣服”的成员
- 同时拥有“书”和“衣服”的成员
例如
Member Book Clothes Both
1 0 0 1
2 1 0 0
3 1 0 0
4 0 1 0
5 0 0 1
6 1 0 0
7 1 0 0
我已经设法让它与子查询一起工作,但由于表的大小,它可能需要 2 多分钟才能运行。
如果有人知道实现这一目标的更好方法,我将不胜感激?
解决方案
一种方法使用条件聚合:
select
memberid,
case when max(producttype) = 'book' then 1 else 0 end book,
case when min(producttype) = 'clothes' then 1 else 0 end clothes,
case when min(producttype) <> max(producttype) then 1 else 0 end both
from test
group by memberid
这是有效的,因为只有两个可能producttype
的 s。如果您实际上有更多,那么您需要一些更复杂(并且可能更有效)的表达式,例如:
case when count(*) = sum(case when producttype = 'book' then 1 end)
then 1
else 0
end book
推荐阅读
- ios - Xcode 预览显示加载页面,然后仅显示白屏
- javascript - 数据表:无法从搜索字段中搜索数据表
- python - 将值附加到新的链接列表
- android - 如何解码有效载荷并获取 JWT 有效载荷中的值
- django - 如果数据库中存在数据,则禁用表单字段
- python - 如何下载包含交互式条形图数据但没有 URL,只有 XPath 的文本文件?硒是一种有效的解决方案吗?
- python - 使用node js中的pythonshell包将python脚本连接到node js
- java - 实用函数对 Array 类的正确签名:Comparable
或可比? - php - docker 组合多个项目
- javascript - Brain.js 人工神经网络预测缺失变量值