具有不同条件的聚合函数

时间:2016-07-07 14:31:40

标签: sql sql-server

我有这个简单的查询:

SELECT
a.new_funderidname as Funder,
COUNT(a.new_funderidname) as Units
FROM new_dealsheet a
LEFT JOIN salesorder B ON a.new_dsheetid = B.salesorderid
WHERE a.New_PassedToAdmin = 1
GROUP BY a.new_funderidname
ORDER BY Units desc

没关系,但我的B表包含另一个名为maint的字段,我还需要获取这两个可能值的计数,例如

SELECT
a.new_funderidname as Funder,
COUNT(a.new_funderidname) as Units,
COUNT(a.new_funderidname) **WHERE b.maint=1 as UnitsMaint**,
COUNT(a.new_funderidname) **WHERE b.maint=0 as UnitsNotMaint**
FROM new_dealsheet a
LEFT JOIN salesorder B ON a.new_dsheetid = B.salesorderid
WHERE a.New_PassedToAdmin = 1
GROUP BY a.new_funderidname
ORDER BY Units desc

我可以在一个查询中执行此操作吗?

由于

3 个答案:

答案 0 :(得分:4)

使用CASE

SELECT
a.new_funderidname as Funder,
COUNT(a.new_funderidname) as Units,
sum(case when b.maint=1 then 1 else 0 end ) as UnitsMaint,
sum(case when b.maint=0 then 1 else 0 end ) as UnitsNotMaint,
FROM new_dealsheet a
LEFT JOIN salesorder B ON a.new_dsheetid = B.salesorderid
WHERE a.New_PassedToAdmin = 1
GROUP BY a.new_funderidname 
ORDER BY Units desc

答案 1 :(得分:1)

如果maint始终为0或1,您可以将它们与Sum(b.mainnt)Sum(1-b.mainnt)

相加
SELECT
a.new_funderidname as Funder,
COUNT(a.new_funderidname) as Units,
Sum(b.mainnt) as UnitsMaint,
Sum(1 - b.mainnt) as UnitsNotMaint
FROM new_dealsheet a
LEFT JOIN salesorder B ON a.new_dsheetid = B.salesorderid
WHERE a.New_PassedToAdmin = 1
GROUP BY a.new_funderidname 
ORDER BY Units desc

如果b.mainnt属于Sum类型,则可能需要在bit内进行投射:例如: SUM(cast(b.mainnt as int))SUM(1 - cast(b.mainnt as int))

答案 2 :(得分:0)

你可以使用PIVOT功能。

select Funder,
UNITSMAINT+UNITSNOTMAINT as UNITS,
UNITSMAINT,
  UNITSNOTMAINT 
    from
(
SELECT
a.new_funderidname as Funder,b.Maint
FROM new_dealsheet a
LEFT JOIN salesorder B ON a.new_dsheetid = B.salesorderid
WHERE a.New_PassedToAdmin = 1
)
PIVOT 
   (
    count(b.Maint) 
     For(1 as UNITSMAINT,0 as UNITSNOTMAINT)
   );

参考Pivot function