Chance Group By子句用于正确的T-SQL中的Select语句

时间:2014-02-24 06:28:39

标签: sql sql-server tsql

我有以下2个查询: 1)

SELECT *
FROM [FUNDS]     
WHERE YEAR(DATE) = 2014 AND MONTH(DATE) = 1
AND TRANSACTION_TYPE LIKE 'OT%'
AND CURRENCY != 'EUR'
AND PPC IN(1,2,3)                               
AND OC_RESID = 1 AND BNF_RESID = 2 

这给了我:

ID    TRANSACTION_TYPE     AMOUNT    OC_RESID      BNF_RESID
1      OT                  111         1              2
2      OT                  222         1              2

2)

SELECT *
FROM [FUNDS]     
WHERE YEAR(DATE) = 2014 AND MONTH(DATE) = 1
AND TRANSACTION_TYPE LIKE 'OT%'
AND CURRENCY != 'EUR'
AND PPC IN(1,2,3)                               
AND OC_RESID = 2 AND BNF_RESID = 2 

这给了我:

ID    TRANSACTION_TYPE     AMOUNT    OC_RESID      BNF_RESID
8      OT                  333         2              2
9      OT                  444         2              2

我想将它们合并为一个SELECT语句:

 SELECT 
    ISNULL((CASE WHEN OC_RESID = 1 AND BNF_RESID = 2 THEN SUM(AMOUNT) END),0) as AB,
    ISNULL((CASE WHEN OC_RESID = 2 AND BNF_RESID = 2 THEN SUM(AMOUNT) END),0) as BB
 FROM [FUNDS]     
 WHERE YEAR(DATE) = 2014 AND MONTH(DATE) = 1
 AND TRANSACTION_TYPE LIKE 'OT%'
 AND CURRENCY != 'EUR'
 AND PPC IN(1,2,3)
 GROUP BY OC_RESID, BNF_RESID 

这里我将两个SUM放在不同的行中:

AB        BB
333       0
0         777

但这是错的,我需要得到这样的结果:

AB        BB
333       777

我认为问题出在GROUP BY子句中,但我无法逃脱它。

我还想在SELECT中转义子查询,因为我在WHERE子句中有很多条件。

我将不胜感激任何帮助!

2 个答案:

答案 0 :(得分:1)

您好我们也可以这样使用union all和CTE

;WITH CTE AS
(
Select SUM(AMOUNT) From FUNDS a WHERE  a.OC_RESID = 1  AND a.BNF_RESID = 2 AS AA
UNION ALL
Select SUM(AMOUNT) From FUNDS b WHERE  b.OC_RESID = 2  AND b.BNF_RESID = 2 AS BB
WHERE   YEAR(DATE) = 2014 AND MONTH(DATE) = 1
     AND a.TRANSACTION_TYPE LIKE 'OT%'
     AND a.CURRENCY != 'EUR'
     AND a.PPC IN(1,2,3)
 GROUP BY a.OC_RESID, a.BNF_RESID 
 )
 Select SUM(AA),SUM(BB) FRom CTE 

答案 1 :(得分:0)

您可以尝试删除案例陈述中的ISNULL吗?这就是为什么每一行都会得到0的原因。然后你可能会这样做:

SELECT
 SUM(lineAB) [AB],
 SUM(lineBB) [BB]
FROM
(
SELECT 
    CASE WHEN OC_RESID = 1 AND BNF_RESID = 2 THEN SUM(AMOUNT) END as lineAB,
    CASE WHEN OC_RESID = 2 AND BNF_RESID = 2 THEN SUM(AMOUNT) END as lineBB
 FROM [FUNDS]     
 WHERE 
    YEAR(DATE) = 2014 AND MONTH(DATE) = 1
     AND TRANSACTION_TYPE LIKE 'OT%'
     AND CURRENCY != 'EUR'
     AND PPC IN(1,2,3)
 GROUP BY OC_RESID, BNF_RESID 
) tbl