在分组条件求和中使用数组

时间:2019-04-19 15:01:51

标签: sql sql-server

我有可以正常工作的sql查询

SELECT
    CAST(L.CreationUtcDateTime AS DATE),
    SUM(L.Profit),
    SUM(CASE WHEN (L.Network = 0 OR L.Network = 1) THEN L.Profit ELSE 0 END),
    SUM(CASE WHEN (L.Network != 0 AND L.Network != 1) THEN L.Profit ELSE 0 END)

FROM
    [dbo].[Leads] L WITH (NOLOCK)
    LEFT JOIN [dbo].[Transactions] S WITH (NOLOCK) ON L.TransactionId = S.Id

GROUP BY    
    CAST(L.CreationUtcDateTime AS DATE);

我需要通过使用变量而不是硬编码常量来使其更通用。 我将查询更改为:

DECLARE @matchNetworks TABLE (id int)
INSERT @matchNetworks(id) VALUES (0),(1)


SELECT
    CAST(L.CreationUtcDateTime AS DATE),
    SUM(L.Profit),
    SUM(CASE WHEN (L.Network in (SELECT ID from @matchNetworks)) THEN L.Profit ELSE 0 END),
    SUM(CASE WHEN (L.Network not in (SELECT ID from @matchNetworks)) THEN L.Profit ELSE 0 END)

FROM
    [dbo].[Leads] L WITH (NOLOCK)
    LEFT JOIN [dbo].[Transactions] S WITH (NOLOCK) ON L.TransactionId = S.Id

GROUP BY    
    CAST(L.CreationUtcDateTime AS DATE);

现在我有一个错误: 无法对包含聚合或子查询的表达式执行聚合函数。

如何在查询中使用预定义的网络ID数组以避免错误?

1 个答案:

答案 0 :(得分:0)

使用FROM将比较移至LEFT JOIN子句:

SELECT CAST(L.CreationUtcDateTime AS DATE),
       SUM(L.Profit),
       SUM(CASE WHEN mn.ID IS NOT NULL THEN L.Profit ELSE 0 END),
       SUM(CASE WHEN mn.ID IS NULL THEN L.Profit ELSE 0 END)    
FROM [dbo].[Leads] L LEFT JOIN
     [dbo].[Transactions] S 
     ON L.TransactionId = S.Id LEFT JOIN
     @matchNetworks mn
     ON mn.ID = l.Network
GROUP BY CAST(L.CreationUtcDateTime AS DATE);