我有一个3列的数据库表
RecordID Deleted CardHolderID
1963 1 9
4601 1 9
6996 0 9
1532 1 11
1529 0 20
我想要一个SQL查询来输出按CardHolderID分组的Deleted列的行总数。
但是下面的查询将输出2列CardHolderID
select c.CardHolderID, c.Deleted, COUNT(*) as Sum
from Card c
group by c.Deleted, c.CardHolderID
CardHolderID Deleted Sum
9 0 1
9 1 2
20 0 1
11 1 1
我想包括2列,分别为 Deleted0(已删除列等于0的行数)和 Deleted1(已删除列等于1的行数) < / p>
CardHolderID Deleted0 Deleted1
9 1 2
20 1 0
11 1 1
如何对这样的结果进行SQL查询?
亲切的问候
答案 0 :(得分:1)
GROUP BY
单独的CardHolderID。
使用SUM(Deleted)
来计算1。
使用SUM(1-deleted)
来计数0。
select c.CardHolderID, sum(1-c.deleted) deleted0, sum(c.Deleted) deleted1
from Card c
group by c.CardHolderID
答案 1 :(得分:1)
使用条件计数:
select c.CardHolderID,
count( case when c.deleted > 0 then 1 else null end ) deleted0,
count( case when c.deleted = 0 then 1 else null end ) deleted1,
from Card c
group by c.CardHolderID
答案 2 :(得分:0)
如果您使用的是MSSQL
select DtlPivot.CardHolderID, isnull(DtlPivot.[0],0) as Deleted0, isnull(DtlPivot.[1],0) as Deleted1 from
(
select c.CardHolderID, c.Deleted, COUNT(*) as Total from Card c
group by c.Deleted, c.CardHolderID
) aa
PIVOT
(
sum(Total) FOR Deleted IN([0],[1])
)AS DtlPivot