brd
brd

Reputation: 33

Get rows if condition is applicable else single row

I have a case where I have 2 tables, Customers and Transactions.

Many customers may form a customer group (record inside Customers table). I need to show Customers and certain sums in a single row (per group that is) if all of the group's customers has a certain condition (numeric column xCol <> 5). If any one of them (aka at least one) has xCol = 5, I need to show all customers and not the group.

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

TRANSACTIONS TABLE

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

In the above case i will need to show these:

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

Thank you in advance

Upvotes: 3

Views: 108

Answers (2)

A Hocevar
A Hocevar

Reputation: 726

Needs some optimization, but you can go with

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

Upvotes: 0

user359040
user359040

Reputation:

Try:

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

Upvotes: 3

Related Questions