我有一个名为windowLightStatusBar
的sql server 2014表,其中包含此项
Machines
还有另一个名为ID || ProjectName || MachineTypeID || MachineName
----------------------------------------------------------------------
1 || project1 || 1 || m1
1 || project2 || 2 || m2
1 || project1 || 2 || m3
1 || project2 || 1 || m4
1 || project1 || 2 || m5
的表,其中包含这些项目
MachineTypes
所有人都想用此输出写一个查询
Id || Title
-------------------
1 || BigMachine
2 || SmallMachine
我希望有可能
答案 0 :(得分:2)
编辑(在您发布示例之后)
此查询应为您提供所需的结果。我很确定这个问题的解决方案已经在这里@ SO。
链接到sqlfiddle:http://www.sqlfiddle.com/#!9/e3ef7a/1
select ProjectName,
sum(case when MachineTypeID=1 then 1 else 0 end) as BigCount,
sum(case when MachineTypeID=2 then 1 else 0 end) as SmallCount
from Machines group by ProjectName
答案 1 :(得分:0)
尝试此查询:
declare @t1 table(ID int, ProjectName varchar(10), MachineTypeID int, MachineName varchar(5));
insert into @t1 values
(1, 'project1',1, 'm1'),
(1, 'project2',2, 'm2'),
(1, 'project1',2, 'm3'),
(1, 'project2',1, 'm4'),
(1, 'project1',2, 'm5');
declare @t2 table (Id int, Title varchar(20));
insert into @t2 values
(1, 'BigMachine'),
(2, 'SmallMachine');
select ProjectName,
max(case when MachineTypeId = 1 then cnt end) BigMachineCount,
max(case when MachineTypeId = 2 then cnt end) SmallMachineCount
from (
select ProjectName, MachineTypeId, count(*) cnt from @t1
group by ProjectName, MachineTypeId
) a group by ProjectName