使用Sum函数和基于条件的案例函数

时间:2014-05-02 19:09:39

标签: sql sql-server-2012 db2

SQL新手。我有以下查询,我需要将其修改为每个DMA的最佳家庭数,其中AverageHouseHoldIncome大于75K / dateendedstandard。相反,我必须为所有AverageHouseholdIncomes做同样的事情,不到75k。我完全不知道该怎么做。对于学习经历的一些解释,我将不胜感激。

select c.KeyDMA as 'KeyDMA',
C.DMAName as 'DMAName',
a.DateEndedStandard as 'DateEndedStandard',
a.AverageHouseHoldIncome,
a.HouseholdsBest
from lookup..demographiccbg a
join InternalUseOnly..BlockGroupDMAMap  b on a.blockgroupfips = b.blockgroupfips
join lookup..dma c on b.keydma = c.keydma
where a.updoperation < 2
and b.updoperation < 2
and c.updoperation < 2
and c.updoperation < 2
and a.dateendedstandard = '12-31-2013'

最佳,

1 个答案:

答案 0 :(得分:0)

试试这个

select c.KeyDMA as 'KeyDMA',
       C.DMAName as 'DMAName',
       a.DateEndedStandard as 'DateEndedStandard',
       SUM(
            CASE WHEN a.AverageHouseHoldIncome > 75000
                 THEN a.HouseholdsBest
                 ELSE NULL
            END
          ) as 'BestAbove75K',
       SUM(
            CASE WHEN a.AverageHouseHoldIncome <= 75000
                 THEN a.HouseholdsBest
                 ELSE NULL
            END
          ) as 'BestLess75K'
  from lookup..demographiccbg a
  join InternalUseOnly..BlockGroupDMAMap  b on a.blockgroupfips = b.blockgroupfips
  join lookup..dma c on b.keydma = c.keydma
  where a.updoperation < 2
    and b.updoperation < 2
    and c.updoperation < 2
    and a.dateendedstandard = '12-31-2013'
  GROUP BY 
           c.KeyDMA,
           C.DMAName,
           a.DateEndedStandard