2012-10-24 53 views
0

我有一个表叫Phone_Details和数据的模样:分组和总发行

Name   DeviceType InvoiceDate TotalCharges 
Aguilera, Alex Smart Phone 8/3/2012 606.55 
Aguilera, Alex Data Card 8/3/2012 26.17 

我想输出:

Name   Total Spend # of devices Avg Spend # of Bills >300 
Aguilera, Alex 632.72    2   316.36   1 

我试着这样做:

Select Name,Sum(Totalcharges), Count(DeviceType),Sum(Totalcharges)/Count(DeviceType) 
from dbo.Phone_Details 
group by Name 

但是我怎样才能得到最后一列呢?

回答

2
Select Name, 
     Sum(Totalcharges) [Total Spend], 
     Count(DeviceType) [# of devices], 
     Sum(Totalcharges)/Count(DeviceType) [Avg Spend], 
     Count(CASE WHEN TotalCharges > 300 then 1 end) [# of Bills > 300] 
    from dbo.Phone_Details 
group by Name 
+0

应该是'SUM(CASE)'而不是'COUNT(CASE)','因为COUNT(0)'仍然登记1 –

+0

@迈克尔还是 “调试” 为你评论。 :)它是固定的。当我计数时,我通常使用暗示ELSE NULL的COUNT版本。 – RichardTheKiwi

+0

@RichardTheKiwi非常感谢你!不知道为什么我错过了这个逻辑:) – peter