【问题标题】:How to write sql to do one aggregation over another如何编写sql来对另一个进行聚合
【发布时间】:2022-12-11 13:10:44
【问题描述】:

样本数据

WITH
    tbl AS
        (
            Select 'UK'  "CUST_GRP", '00001' "CUST_ID", 'John'  "CUST_NAME", '001' "ORDER_ID", 'Beer' "GOODS" From Dual Union All
            Select 'ITA' "CUST_GRP", '00002' "CUST_ID", 'Jack'  "CUST_NAME", '002' "ORDER_ID", 'Coca Cola' "GOODS" From Dual Union All
            Select 'ITA' "CUST_GRP", '00002' "CUST_ID", 'Jack'  "CUST_NAME", '003' "ORDER_ID", 'Fanta' "GOODS" From Dual Union All
            Select 'ITA' "CUST_GRP", '00003' "CUST_ID", 'Lisa'  "CUST_NAME", '004' "ORDER_ID", 'Beer' "GOODS" From Dual Union All
            Select 'ITA' "CUST_GRP", '00003' "CUST_ID", 'Lisa'  "CUST_NAME", '005' "ORDER_ID", 'Coffee' "GOODS" From Dual Union All
            Select 'FRA' "CUST_GRP", '00004' "CUST_ID", 'Messi' "CUST_NAME", '006' "ORDER_ID", 'Wine' "GOODS" From Dual Union All
            Select 'FRA' "CUST_GRP", '00004' "CUST_ID", 'Messi' "CUST_NAME", '007' "ORDER_ID", 'Juice' "GOODS" From Dual Union All
            Select 'FRA' "CUST_GRP", '00004' "CUST_ID", 'Messi' "CUST_NAME", '008' "ORDER_ID", 'Beer' "GOODS" From Dual Union All
            Select 'FRA' "CUST_GRP", '00005' "CUST_ID", 'Mary'  "CUST_NAME", '009' "ORDER_ID", 'Wine' "GOODS" From Dual Union All
            Select 'FRA' "CUST_GRP", '00005' "CUST_ID", 'Mary'  "CUST_NAME", '020' "ORDER_ID", 'Else' "GOODS" From Dual 
        )

我需要知道完成相同数量订单的客户数量。

预期结果应该是

TEXT
the amount of customers who ordered 1 times is 1
the amount of customers who ordered 2 times is 3
the amount of customers who ordered 3 times is 1

或者

Orders Customers
1 1
2 3
3 1

任何人都可以告诉我如何编写此 SQL?

【问题讨论】:

  • 你能详细解释一下你是如何得出结果的吗?
  • Stack Overflow 不是免费的代码编写服务。请展示您当前的尝试并描述它的问题所在。并提供算法的一般性描述
  • 您正在描述组函数和聚合函数

标签: sql oracle


【解决方案1】:

这将为您带来理想的结果。您正在按客户分组以了解他们下了多少订单。然后也对该子集进行分组。

select orders, count(*) customers
from (
   select cust_id, count(*) orders
   from tbl
   group by cust_id
   )
group by orders   

【讨论】:

    猜你喜欢
    • 2021-09-26
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多