首页 > 解决方案 > 获取行数据的计数

问题描述

有一个表变量(这里我把它写成一个普通的表)

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 多分钟才能运行。

如果有人知道实现这一目标的更好方法,我将不胜感激?

标签: sqlsql-servertsqlgroup-bypivot

解决方案


一种方法使用条件聚合:

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

推荐阅读