1

I am counting specific things in a SQL Server table. I am using multiple count queries, but I am wondering if it's possible to combine them into a single query with the column name and count numbers in a single table for display.

My queries are:

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)

I tried a couple stupid things to combine them, but they were a failure. I honestly can't even begin to think how to combine them, maybe it's not possible?

Thanks!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dizzy49
  • 1,360
  • 24
  • 35

2 Answers2

2

You could use CASE expression to perform conditional aggregation:

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
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
0

Use conditional aggregation:

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;

I would write the logic like this, though:

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;

Doing a left() on a column and then checking the length is redundant. Just use =.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786