将SUMIF转换为TSQL

时间:2016-08-09 14:08:31

标签: sql-server tsql

我有以下代码和以下在SQL Server Management Studio 2012中编写的查询;

WITH cteUniqueClients AS 
(
    SELECT  
        CASE
           WHEN ServiceActualEndDate IS NULL
                AND LAG(ClientID,1) OVER(PARTITION BY ClientID, ServiceProvider ORDER BY ServiceActualEndDate DESC, StartDateFormatted DESC) = ClientID
              THEN 0
           WHEN ServiceActualEndDate IS NOT NULL
              THEN 0
           ELSE 1
        END AS UniqueClient,
        CASE 
           WHEN LAG(ActualHoursPerWeek,1) OVER (PARTITION BY ClientID, ServiceProvider ORDER BY StartDateFormatted DESC) = ActualHoursPerWeek
              THEN 0
              ELSE 1
        END AS UniqueService,
        ClientID, ClientName,
        ActualHoursPerWeek,
        ServicePlannedStartDate, ServiceActualStartDate
    FROM 
        dbo.tTable1
    WHERE
        (ServiceActualStartDate <= '2016-08-09' OR ServicePlannedStartDate <= '2016-08-09')
        AND ServiceActualEndDate IS NULL
        AND (ServicePlannedEndDate > '2016-08-09' OR ServicePlannedEndDate IS NULL)
        AND ClientDeathDate IS NULL         
)
SELECT 
    COUNT(ClientID) OVER (PARTITION BY ClientID ORDER BY ClientID) AS RecordCount,
    cteUniqueClients.*
FROM 
    cteUniqueClients
WHERE 
    UniqueService = 1
ORDER BY 
    ClientID ASC

以下Excel公式:

=SUMIF(G2:G961,G2,I2:I961) 

其中G列为ClientID,第I列为ActualHoursPerWeek

有没有办法在保留所有报告栏的同时将这两个结合起来?

下面是需要的示例Excel输出的图像;

Updated Excel Output

1 个答案:

答案 0 :(得分:0)

抱歉......忙碌的一天:-)如上所述,我相信有办法做到这一点。不过我认为这里的关键是关注你的订单排序。我编写了以下代码,通过警告为您提供所需的代码。我收录了我的测试表。

declare @tbl table (
Ident                   int identity (1,1),
RecordCount             int,
UniqueClient            int,
ClientID                int,
ClientName              varchar(20),
ActualHoursPerService   float
);

insert into @tbl values
(1,1,1,'Pam',18.75),
(1,1,2,'Collin',8.75),
(1,1,3,'William',19.83),
(1,1,4,'Andy',10),
(5,0,5,'James',1.19),
(5,0,5,'James',1.75),
(5,0,5,'James',2.31),
(5,0,5,'James',3.5),
(5,0,5,'James',7),
(1,1,6,'Ford',12)

select * from @tbl order by ClientID;

select  sum(t.ActualHoursPerService) over (partition by t.ClientID order by t.Ident desc rows unbounded preceding) HoursPerClient
        ,*
from    @tbl t
order   by t.ClientID, t.Ident;

您会注意到我在源表中创建了一个Ident列(这将是您的CTE。否则,James的行可能会出现故障,然后每行会有不同的运行总计。应该在分区声明中选择ServiceActualEndDate作为您的订单,并在最终排序中使用它。

作为参考,这里有一个运行总计的方法列表,我将其作为反向运行总计以匹配您要查看的内容:link

希望这足以让你到达那里!