TSQL仅在另一列中满足条件时对列进行分组

时间:2018-01-25 18:20:34

标签: tsql having

此查询的结果有多个transactionCodes。我想仅在applyToLineID ='0'时才对事务代码进行分组。换句话说,如果applyToLineID不是0,则不应对事务代码进行分组。我认为这可以通过HAVING语句来完成,但我无法让它工作。下面你会发现2段代码,第一段是我的原始代码,第二段是原始代码加上我尝试执行上述分组。

原始代码:

SELECT 
ar.arlineitemid,
ar.siteid,
ar.transactioncode,
ar.description,
ar.amount,
ar.balance,
ar.applytolineid,
ar.posteddate,
TC.transactioncode,
TC.arlineitemid

FROM tswdata.dbo.t_arlineitem as AR     

left JOIN

(
SELECT

ar2.transactioncode,
ar2.arlineitemid

FROM tswdata.dbo.t_arlineitem as ar2    

WHERE  

ar2.SiteID = '101'
AND
(AR2.Transactioncode LIKE 'A%'  And
AR2.Transactioncode NOT LIKE 'AS%' And
AR2.Transactioncode NOT LIKE 'AF%' And
AR2.Transactioncode NOT LIKE 'AX%')
) TC

ON
ar.applytolineid = TC.arlineitemid

WHERE  

ar.SiteID = '101'
AND
AR.Transactioncode <> 'A18'

我尝试执行条件分组的代码:

SELECT 
ar.arlineitemid,
ar.siteid,
ar.transactioncode,
ar.description,
ar.amount,
ar.balance,
ar.applytolineid,
ar.posteddate,
TC.transactioncode,
TC.arlineitemid

FROM tswdata.dbo.t_arlineitem as AR     

left JOIN

(
SELECT

ar2.transactioncode,
ar2.arlineitemid

FROM tswdata.dbo.t_arlineitem as ar2    

WHERE  

ar2.SiteID = '101'
AND
(AR2.Transactioncode LIKE 'A%'  And
AR2.Transactioncode NOT LIKE 'AS%' And
AR2.Transactioncode NOT LIKE 'AF%' And
AR2.Transactioncode NOT LIKE 'AX%')
) TC

ON
ar.applytolineid = TC.arlineitemid

WHERE  

ar.SiteID = '101'
AND
AR.Transactioncode <> 'A18'

GROUP BY 
ar.transactioncode,

HAVING
ar.ApplyTolineId = '0'

2 个答案:

答案 0 :(得分:2)

您可以联合两个查询:一个包含除交易代码为0的项目之外的所有查询,另一个查询仅包含事务代码为0的项目的聚合。

答案 1 :(得分:1)

考虑像这样解决你的问题:

您要查看两组数据 - applyToLineID = '0'applyToLineID <> '0'的数据。

您有一个查询可以提取两个集合用于评估applyToLineID逻辑的原始信息。

您的解决方案可能类似于:

SELECT * FROM
    (select common data, Grouped Values from (common_query) where applyToLineID = 0)
UNION
SELECT * FROM
    (select common data, unGrouped Values from (common_query) where applyToLineID <> 0)