有没有办法避免GROUP BY

时间:2017-05-18 22:07:44

标签: sql sql-server tsql

我的表中包含ID,Perdium和Location等列,因此我想计算给予员工的所有perdium和NY中给出的perdium份额。我面临的问题是SQL Server引擎正在抛出错误,说明GROUP BY子句中不存在位置列(根据我的用例需要)。如果我在Group By子句中包含该位置,我总是得到NYPerdiumShare因为1不是我所期待的。这有什么解决方法吗?

WITH CTE_Employee AS
    (
        SELECT  ID,
                SUM(Perdium) AS TotalPerdium,
                CASE WHEN Location='NY' THEN SUM(Perdium) ELSE NULL END AS NYPerdium FROM EmployeePerdium
        GROUP BY ID
    )

SELECT  ID,
        TotalPerdium,
        NYPerdium/TotalPerdium AS NYPerdiumShare 
    FROM CTE_Employee

2 个答案:

答案 0 :(得分:2)

您可以通过重写查询来消除除ID以外的任何内容以进行分组的需要,如下所示隐藏聚合函数中的CASE

WITH CTE_Employee AS (
    SELECT
        ID
    ,   SUM(Perdium) AS TotalPerdium
    ,   SUM(CASE WHEN Location='NY' THEN Perdium ELSE 0 END) AS NYPerdium
    FROM EmployeePerdium
    GROUP BY ID
)
SELECT
    ID
,   TotalPerdium
,   NYPerdium/TotalPerdium AS NYPerdiumShare 
FROM CTE_Employee

答案 1 :(得分:1)

你不需要这里的cte。只需使用sum窗口函数。

SELECT DISTINCT
ID,
SUM(Perdium) OVER() as TotalPerdium
SUM(CASE WHEN Location='NY' THEN 1.0*Perdium ELSE 0 END) OVER(PARTITION BY ID)
/SUM(Perdium) OVER() AS NYPerdium 
FROM EmployeePerdium