【问题标题】:How to count distinctly with conditions?如何区分条件?
【发布时间】:2021-11-04 20:03:30
【问题描述】:

我有一个类似这样的查询,它给出了每个产品和集群有多少家商店。

SELECT product,
         cluster,
         count(distinct shop_id) AS shops
FROM a
WHERE site = 1 
GROUP BY  1, 2 

但是,我想看看每个产品是否有其他商店具有相同的集群。所以,如果有其他商店(> 1)YES,如果没有(

    product | other_shops
    X            Yes
    Y            No

我该怎么做?

【问题讨论】:

  • 向我们展示一些示例表数据和预期结果 - 全部为格式化文本(不是图像)。即minimal reproducible example.
  • 为什么集群不是结果的一部分?结果表应该有:product、cluster、other_shops?

标签: sql amazon-web-services amazon-athena


【解决方案1】:

您可以将distinctcountgroup bycase 语句一起使用以在新列中显示yesno。我已经创建了一组示例数据来演示使用原始 SQL,但我相信它对于 Athena 控制台会非常相似。试试this link to the live demo(我不知道它可以持续多久)。

示例数据和包含productclustershop 列的表。

CREATE TABLE t1 (
 product TEXT,
 cluster TEXT,
 shop TEXT
);
INSERT INTO t1 VALUES 
('p1', 'c1', 's1'), ('p1', 'c1', 's2'), ('p1', 'c1', 's3'), 
('p1', 'c2', 's1'), ('p1', 'c2', 's2'), ('p1', 'c2', 's3'), 
('p1', 'c3', 's1'), ('p1', 'c3', 's2'), ('p1', 'c3', 's3'), 
('p2', 'c1', 's1'), ('p2', 'c1', 's2'), ('p2', 'c1', 's3'),
('p2', 'c2', 's1'), ('p2', 'c2', 's2'), ('p2', 'c2', 's3'),
('p2', 'c3', 's1'), 
('p3', 'c1', 's1');

查询

SELECT DISTINCT cluster, product, count(shop) AS qtd, 
CASE WHEN count(shop) > 1 THEN 'YES' ELSE 'NO' END AS other_shops
FROM t1 
group by cluster, product;

输出将是

Cluster|product|shop qtd|other_shops
c1|p1|3|YES
c1|p2|3|YES
c1|p3|1|NO
c2|p1|3|YES
c2|p2|3|YES
c3|p1|3|YES
c3|p2|1|NO

【讨论】:

    猜你喜欢
    • 2018-08-01
    • 1970-01-01
    • 2022-01-19
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多