如何将这四个请求合并为一个?
Select COUNT(Table1.statusID) as result1 from Table1 where Table1.emplDesignerID = 1135 and Table1.cancelled = 0
Select COUNT(Table1.statusID) as result2 from Table1 where Table1.emplDesignerID = 26 and Table1.cancelled = 0
Select COUNT(Table1.statusID) as result3 from Table1 where Table1.emplDesignerID = 1086 and Table1.cancelled = 0
Select COUNT(Table1.statusID) as result4 from Table1 where Table1.emplDesignerID = 1089 and Table1.cancelled = 0
我正在使用MS SQL Server。
答案 0 :(得分:5)
SUM
和CASE
可以在这里有用地组合:
Select
SUM(CASE WHEN Table1.emplDesignerID = 1135 THEN 1 ELSE 0 END) as result1,
SUM(CASE WHEN Table1.emplDesignerID = 26 THEN 1 ELSE 0 END) as result2,
SUM(CASE WHEN Table1.emplDesignerID = 1086 THEN 1 ELSE 0 END) as result3,
SUM(CASE WHEN Table1.emplDesignerID = 1089 THEN 1 ELSE 0 END) as result4
from Table1
where Table1.cancelled = 0
and Table1.emplDesignerID in (1135,26,1086,1089)
根据使用情况,您可能会或可能不会认为IN
子句中需要WHERE
过滤器。还有其他可能的转换(在emplDesignerID
子句中包含SELECT
,并在其上加上GROUP
),这可能会使它更加灵活。
答案 1 :(得分:1)
您可以简单地使用子查询,并将其组合为一个更大的查询。
select
(
Select COUNT(Table1.statusID) as result1 from Table1 where Table1.emplDesignerID = 1135 and Table1.cancelled = 0
) as result1,
(
Select COUNT(Table1.statusID) as result2 from Costs where Table1.emplDesignerID = 26 and Table1.cancelled = 0
) as result2,
(
Select COUNT(Table1.statusID) as result3 from Costs where Table1.emplDesignerID = 1086 and Table1.cancelled = 0
) as result3,
(
Select COUNT(Table1.statusID) as result4 from Costs where Table1.emplDesignerID = 1089 and Table1.cancelled = 0
) as result4;
如果您使用的是Oracle,则必须添加from dual
。
某些其他数据库(例如MS SQL)不需要它。
Oracle提供了双重表,因此可以添加附加的from dual
。
MS SQL提供了不使用from语句进行查询的功能。
或者让我们拥有Values
功能:
select
(
Select COUNT(Table1.statusID) as result1 from Table1 where Table1.emplDesignerID = 1135 and Table1.cancelled = 0
) as result1,
(
Select COUNT(Table1.statusID) as result2 from Costs where Table1.emplDesignerID = 26 and Table1.cancelled = 0
) as result2,
(
Select COUNT(Table1.statusID) as result3 from Costs where Table1.emplDesignerID = 1086 and Table1.cancelled = 0
) as result3,
(
Select COUNT(Table1.statusID) as result4 from Costs where Table1.emplDesignerID = 1089 and Table1.cancelled = 0
) as result4
from
(VALUES ('dummyValue'));
答案 2 :(得分:0)
如果只有count()是您需要的结果,则可以使用UNION:
Select COUNT(Table1.statusID) as result1 from Table1 where Table1.emplDesignerID = 1135 and Table1.cancelled = 0
UNION
Select COUNT(Table1.statusID) as result2 from Table1 where Table1.emplDesignerID = 26 and Table1.cancelled = 0
UNION
Select COUNT(Table1.statusID) as result3 from Table1 where Table1.emplDesignerID = 1086 and Table1.cancelled = 0
UNION
Select COUNT(Table1.statusID) as result4 from Table1 where Table1.emplDesignerID = 1089 and Table1.cancelled = 0
它很容易阅读,但效率不高