sql server计数字段的不同值
我有两个表格:sql server计数字段的不同值,sql,sql-server,tsql,distinct,Sql,Sql Server,Tsql,Distinct,我有两个表格:目录和包装 在内容中列如下所示: Id Name IsPerishable IsSpecial IsDanger ---------------------------------------------------------- 1 Paper False False False 3 Fruit True False
目录
和包装
在内容中
列如下所示:
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
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 Perishable Special Danger
-----------------------------------------------
ATL 2 1 0
BAQ 0 1 1
在包中
列如下所示:
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
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 Perishable Special Danger
-----------------------------------------------
ATL 2 1 0
BAQ 0 1 1
现在我想要一个结果,将每个“To”分组,然后显示IsPerishable/IsSpecial/IsDanger的单独值
像这样:
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
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 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
试试这个
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个内部查询完成,并在外部查询中使用内置标量SQL函数