我需要有一个cust_valid“ A”和cust_valid“ I”的客户(每个客户2行)。
select c.cust_first_name || ' ' || c.cust_last_name as customer_name,
c.cust_valid from customers c
join sales s on s.cust_id = c.cust_id
where c.cust_valid like '%A%' or
c.cust_valid like '%I%'
group by c.cust_first_name, c.cust_last_name, c.cust_credit_limit, c.cust_valid
having sum(s.amount_sold) > c.cust_credit_limit * 500;
我的输出是所有拥有cust_valid的A或I的客户。我只需要输出同时拥有两个(两行)的客户
我尝试使用AND而不是OR,但由于在任何行中我们都没有I或A,因此会给我一个空表。
答案 0 :(得分:1)
在查询中使用cte
,在group by customer_name
中使用cust_valid
,这样您就只能在with cte as (
select c.cust_first_name || ' ' || c.cust_last_name as customer_name,
c.cust_valid from customers c
join sales s on s.cust_id = c.cust_id
where c.cust_valid like '%A%' or c.cust_valid like '%I%'
group by c.cust_first_name, c.cust_last_name, c.cust_credit_limit, c.cust_valid
having sum(s.amount_sold) > c.cust_credit_limit * 500
)
select * from cte
where customer_name in (
select customer_name
from cte
group by customer_name
having count(distinct cust_valid) = 2
)
中获得A和I的客户:
Promise.all
答案 1 :(得分:0)
您需要执行SELF_JOIN
,还需要从GROUP BY中删除CUST_VALID
,因为对于同一位客户而言,它是不同的
SELECT
C.CUST_FIRST_NAME
|| ' '
|| C.CUST_LAST_NAME AS CUSTOMER_NAME,
LISTAGG(C.CUST_VALID,',') WITHIN GROUP (ORDER BY C.CUST_VALID) AS CUST_VALID
-- CUST_VALID IS DIFFERENT FOR SAME CUSTOMERS SO LISTAGG IS USED TO GET ALL THE CUST_VALID
FROM
CUSTOMERS C
JOIN SALES S ON S.CUST_ID = C.CUST_ID
JOIN CUSTOMERS C1 ON (C.<UNIQUE_KEYS> = C1.<UNIQUE_KEYS>)
WHERE
C.CUST_VALID LIKE '%A%'
AND C1.CUST_VALID LIKE '%I%' -- CONDTITION IS CHANGED TO C1
GROUP BY
C.CUST_FIRST_NAME,
C.CUST_LAST_NAME,
C.CUST_CREDIT_LIMIT
--C.CUST_VALID -- Removed it from GROUP BY
HAVING
SUM(S.AMOUNT_SOLD) > C.CUST_CREDIT_LIMIT * 500;
干杯!
答案 2 :(得分:0)
将检查移至HAVING
子句和COUNT
中,以确保您具有每种行类型之一:
select c.cust_first_name || ' ' || c.cust_last_name as customer_name,
LISTAGG( c.cust_valid, ',' ) WITHIN GROUP ( ORDER BY c.cust_valid ) AS cust_valid
from customers c
join sales s
on s.cust_id = c.cust_id
WHERE c.cust_valid like '%A%'
OR c.cust_valid like '%I%'
group by c.cust_first_name,
c.cust_last_name,
c.cust_credit_limit
having sum(s.amount_sold) > c.cust_credit_limit * 500
AND COUNT( CASE WHEN c.cust_valid like '%A%' THEN 1 END ) > 0
AND COUNT( CASE WHEN c.cust_valid like '%I%' THEN 1 END ) > 0;