一个奇怪的表的聚合

时间:2014-09-17 14:25:03

标签: sql sql-server

丑陋的表

Resource name       PROJECT WeekStarting            Monday  Tuesday Wednesday   Thursday    Friday  Saturday    Sunday  ChargeRate
Dave Y              DELTA   2014-09-01 00:00:00.000 0       1       1           1           0       0               0   20.00
Dave Y              DELTA   2014-09-15 00:00:00.000 0       1       1           1           0       0               0   20.00
Dave Y              DELTA   2014-09-22 00:00:00.000 0       1       1           1           0       0               0   20.00
Dave Y              DELTA   2014-09-29 00:00:00.000 0       1       1           1           0       0               0   20.00
Dave Y              HOLIDAY 2014-09-08 00:00:00.000 1       1       1           1           1       0               0   0.00
Dave Y              HOLIDAY 2014-09-22 00:00:00.000 0       0       0           0           1       0               0   0.00

我必须为所有人提供以下观点。

2014年9月

Resource Name   Days Booked ( Days Worked - Holidays )    Total Rate 
   Dave Y            6      ( 12 - 6)                          120 

还有十月和十一月。

如何在一个查询中通过sql将丑陋的表转换为下表?

1 个答案:

答案 0 :(得分:1)

您需要说明总费率'是来自。但这是完成其余部分的一种方法。

SELECT
    cast(Datepart(m, WeekStarting) as varchar(2)) + '/' + cast(Datepart(yyyy, WeekStarting) as varchar(4)) as [Month]
    , ResourceName
    , SUM (CASE WHEN PROJECT = 'HOLIDAY' THEN -1 ELSE 1 END * (
        Monday + Tuesday + Wednesday + Thursday + Friday + Saturday + Sunday)) AS DaysBooked

FROM
    #UglyTable

GROUP BY
    ResourceName
    , Datepart(m, WeekStarting)
    , Datepart(yyyy, WeekStarting)