可在多个国家/地区使用的SQL SELECT产品

问题描述 投票:0回答:2

我有这张带有市场和价格的水果表(表实际上只是摘录)

Product Market  Price
Apple   UK  4
Apple   DE  5
Apple   US  4
Apple   IT  3
Banana  US  2
Orange  UK  1
Kiwi    ES  3
Kiwi    DE  10
Kiwi    US  12
Kiwi    UK  11
Cucumb  IT  5
Cucumb  DE  4
Cucumb  UK  3
Peach   IT  12
Peach   DE  10
Peach   UK  10
Peach   US  11

现在,我只希望选择(或分组)在DE,英国,IT和美国这四个市场中均可用的产品。该表应显示以下内容:

Product Market  Price
Apple   UK  4
Apple   DE  5
Apple   US  4
Apple   IT  3
Peach   IT  12
Peach   DE  10
Peach   UK  10
Peach   US  11

我已经尝试使用group by + having + Count Distinct,但是它不起作用。见下文

SELECT
market, product, AVG(price) as pr
FROM
    fruits
WHERE       
    market IN (DE, IT, UK, US)
GROUP BY
    market, product
HAVING Count (DISTINCT market=4)

我想我以错误的方式使用了不同的计数。请帮忙。谢谢!

sql count distinct having
2个回答
1
投票
具有-条件Count (DISTINCT market=4)应该是:

SELECT market, product, AVG(price) as pr FROM fruits WHERE market IN (DE, IT, UK, US) GROUP BY market, product HAVING Count (DISTINCT market) = 4


0
投票
您没有产品的重复国家/地区。我建议简单的窗口功能:

select f.* from (select f.*, count(*) over (partition by product) as cnt from fruits f where market in ('DE', 'IT', 'UK', 'US') ) f where cnt = 4;

© www.soinside.com 2019 - 2024. All rights reserved.