3

我有一个案例,我有 2 张桌子,Customers并且Transactions.

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

客户表

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

先感谢您

4

2 回答 2

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
于 2013-03-15T09:21:27.897 回答
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
于 2013-03-15T09:27:28.967 回答