如果条件适用,则获取行,否则单行

时间:2013-03-15 08:47:03

标签: sql sql-server tsql

我有一个案例,我有2个表,CustomersTransactions

许多客户可能会组建一个客户组(记录在Customers表内)。如果所有组的客户都具有特定条件(数字列Customers),我需要在单行(每组中)显示xCol <> 5和某些总和。如果其中任何一个(也就是至少一个)有xCol = 5,我需要向所有客户展示,而不是小组。

CUSTOMERS TABLE

Customer    Group       Customer Code
ALPHA   GROUP A     1
BETA    GROUP A     2
GAMMA   GROUP A     3
DELTA   GROUP B     4
LAMDA   GROUP B     5

交易表

Customer Code   xCol    Amount
1                   1   4
2                   1   4
3                   1   4
4                   5   1
5                   2   2

在上述情况下,我需要展示这些:

Customer    Group       Amount
-----           GROUP A     12
DELTA           GROUP B     1
LAMDA           GROUP B     2

提前谢谢

2 个答案:

答案 0 :(得分:3)

尝试:

with cte as
(select c.*,
        t.Amount,
        max(case xCol when 5 then 1 end) over (partition by c.[Group]) xCol5
 from customers c
 left join transactions t on c.[Customer Code] = t.[Customer Code])
select case xCol5 when 1 then [Customer Code] end [Customer Code],
       [Group],
       sum(Amount) Amount
from cte
group by [Group], case xCol5 when 1 then [Customer Code] end

答案 1 :(得分:0)

需要一些优化,但你可以选择

SELECT *
  FROM (SELECT tc.CUSTOMER, tc.GROUP, tt.AMNT AS AMOUNT
          FROM CUSTOMERS tc
               JOIN TRANSACTIONS  tt
                  ON tc.CUST_CODE = tt.CUST_CODE
               JOIN (SELECT DISTINCT tc.GROUP
                       FROM CUSTOMERS  tc JOIN TRANSACTIONS  tt
                               ON tt.CUST_CODE = tc.CUST_CODE
                      WHERE tt.XCOL = 5) spgrp
                  ON spgrp.GROUP = tc.GROUP)
UNION ALL
(  SELECT '----' AS CUSTOMER, tc.GROUP, SUM (tt.AMNT) AS AMOUNT
     FROM CUSTOMERS  tc
          JOIN TRANSACTIONS  tt
             ON tc.CUST_CODE = tt.CUST_CODE
          JOIN ( (  SELECT DISTINCT GROUP FROM TEST_CUST)
                MINUS
                (SELECT DISTINCT tc.GROUP
                   FROM CUSTOMERS tc JOIN TRANSACTIONS tt
                           ON tt.CUST_CODE = tc.CUST_CODE
                  WHERE tt.XCOL = 5)) othgrp
             ON othgrp.GROUP = tc.GROUP
 GROUP BY tc.GROUP)
ORDER BY 2, 1