分组和总发行

时间:2012-10-24 20:34:37

标签: sql sql-server sql-server-2008 tsql

我有一个名为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

但我怎么能得到最后一栏呢?

1 个答案:

答案 0 :(得分: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