我有一个看起来像这样的表:
CREATE TABLE [dbo].[Phrase]
(
[PhraseId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
[English] NVARCHAR (250) NOT NULL,
[p1] BIT DEFAULT ((0)) NOT NULL,
[p2] BIT DEFAULT ((0)) NOT NULL,
[p3] BIT DEFAULT ((0)) NOT NULL,
PRIMARY KEY CLUSTERED ([PhraseId] ASC),
CONSTRAINT [FK_PhrasePhraseChapter]
FOREIGN KEY ([ChapterId])
REFERENCES [dbo].[PhraseChapter] ([PhraseChapterShortId])
);
我想要做的是得到p1,p2和p3的计数,所以输出看起来像:
p1 100
p2 200
p3 23
请注意,在这种情况下,第一行意味着Phrase表中有100行将p1设置为值1.希望这是有道理的。
我知道我可以使用三列简单地执行此操作,但我需要一个只有两个字符串列的行输出,如上所述。任何人都可以给我一个关于如何实现这个目标的建议吗?
答案 0 :(得分:1)
使用联盟:
select 'P1' as ColToCount,
count(distinct P1) as Counted
from MyTable
where 1=1 -- replace with any criteria
union all
select 'P2' as ColToCount,
count(distinct P2) as Counted
from MyTable
where 1=1 -- replace with any criteria
union all
select 'P3' as ColToCount,
count(distinct P3) as Counted
from MyTable
where 1=1 -- replace with any criteria
如果你只有几件不同的东西可以计算,这真的很好
答案 1 :(得分:1)
您可以使用UNPIVOT
,如下所示:
SELECT myColumn ,
NoOfTrue
FROM ( SELECT [p1] = COUNT(CASE WHEN [p1] = 1 THEN 1 END) ,
[p2] = COUNT(CASE WHEN [p2] = 1 THEN 1 END) ,
[p3] = COUNT(CASE WHEN [p3] = 1 THEN 1 END)
FROM Phrase
) d UNPIVOT
( NoOfTrue FOR myColumn IN ( [p1], [p2], [p3] ) ) piv;
答案 2 :(得分:0)
也许通过使用案例和总和:
SELECT sum(case when p1 = 1 then 1 end) as p1Count,
sum(case when p2 = 1 then 1 end) as p2Count,
sum(case when p3 = 1 then 1 end) as p3Count
FROM Phrase
答案 3 :(得分:0)
select 'p1' p, sum(p1) countp
from Phrase
union all
select 'p2', sum(p2)
from Phrase
union all
select 'p3', sum(p3)
from Phrase;
注意sum
字段使用bit
可以完成您想要的所有操作
bit
字段可以包含(0
- 1
- null
)个值,sum
会将null
值添加为0
;