结合COUNT个查询

时间:2018-12-14 19:58:08

标签: sql sql-server count

我正在统计SQL Server表中的特定内容。我正在使用多个计数查询,但是我想知道是否可以将它们与单个表中的列名和计数编号组合成一个查询。

我的查询是:

select count(*) as Ask_Count
from Pld_OpenSalesOrdersLines
where left(C_Item_ID, 1) = '*'

select count(*) as M_Count
from Pld_OpenSalesOrdersLines
where (left(C_Item_ID, 1) = 'M' and len(C_Item_ID) = 1)

select count(*) as MN_Count
from Pld_OpenSalesOrdersLines
where (left(C_Item_ID, 2) = 'MN' and len(C_Item_ID) = 2)

我尝试了一些愚蠢的方法来将它们结合起来,但是它们都是失败的。老实说,我什至无法开始考虑如何将它们结合起来,也许不可能吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用CASE表达式执行条件聚合:

select 
 COUNT(CASE WHEN LEFT(C_Item_ID,1)='*' THEN 1 END) AS Ask_Count,
 COUNT(CASE WHEN LEFT(C_Item_ID,1)='M' AND LEN(C_Item_ID)=1 THEN 1 END)  M_Count,
 COUNT(CASE WHEN LEFT(C_Item_ID,2)='MN' AND LEN(C_Item_ID)=2 THEN 1 END) MN_Count 
from Pld_OpenSalesOrdersLines

答案 1 :(得分:0)

使用条件聚合:

select sum(case when LEFT(C_Item_ID,1) = '*' then 1 else 0 end) as count_1, 
       sum(case when LEFT(C_Item_ID,1) = 'M' AND LEN(C_Item_ID)=1 then 1 else 0 end) as count_2,
       sum(case when LEFT(C_Item_ID,2) = 'MN' AND LEN(C_Item_ID)=2 then 1 else 0 end) as count_3
from Pld_OpenSalesOrdersLines;

我会这样写逻辑:

select sum(case when C_Item_ID like '*%' then 1 else 0 end) as count_1, 
       sum(case when C_Item_ID = 'M' then 1 else 0 end) as count_2,
       sum(case when C_Item_ID = 'MN' then 1 else 0 end) as count_3
from Pld_OpenSalesOrdersLines;

在列上执行left(),然后检查长度是多余的。只需使用=