sql server count一个字段的不同值

时间:2014-02-01 09:18:16

标签: sql sql-server tsql distinct

我有2个表:ContentsPacks

Content列中的内容如下:

Id    Name            IsPerishable     IsSpecial     IsDanger
----------------------------------------------------------
1     Paper           False            False         False
3     Fruit           True             False         False
5     NewsPaper       False            True          False
6     Radioactive     False            False         True
7     Foods           True             False         False

Packs列中的内容如下:

Id      From        To      ContentId
---------------------------------------
1       ABZ         ATL     3
2       ANU         ATL     5
3       BAQ         ATL     7
4       BTS         BAQ     6
5       FRL         BAQ     5

现在我想要一个结果,将每个'To'分组,然后显示IsPerishable / IsSpecial / IsDanger的单独值

像这样:

To      Perishable      Special        Danger
-----------------------------------------------
ATL     2                1               0
BAQ     0                1               1

我尝试使用一些查询,但它们都没有正常工作:

select Name, 
    case 
        when IsSpecial = 1 then count(IsSpecial) 
        when IsPerishable = 1 then count(IsPerishable) 
        when IsDanger = 1 then count(IsDanger) 
    end as 'Content'
from    Contents 
group by IsSpecial , IsPerishable , IsDanger

select       To,count(DISTINCt Id) as 'Count'
FROM         Packs
GROUP BY     To

2 个答案:

答案 0 :(得分:0)

试试这个

Select To,
     (Select count(*) from Content c where c.Id= p.Id and c.IsSpecial=1) as Special,
     (Select count(*) from Content c where c.Id= p.Id and c.Isperishable=1) as Perishable,
     (Select count(*) from Content c where c.Id= p.Id and c.Isperishable=1) as Danger
from
pack p
group by To

答案 1 :(得分:0)

SELECT P.To, SUM(Perishable), SUM(Special),SUM(Danger) FROM
(
SELECT Id, 
CASE IsPerishable WHEN true THEN 1 ELSE 0 END AS Perishable, 
CASE IsSpecial WHEN true then 1 ELSE 0 END AS Special, 
CASE IsDanger WHEN true then 1 ELSE 0 END AS Danger 
FROM Contents
) C 
Right Join Packs P 
on P.ContentId=C.Id
Group BY P.to