gpt4 book ai didi

mysql - SQL - 通过不同的条件聚合相同的列

转载 作者:可可西里 更新时间:2023-11-01 08:03:25 25 4
gpt4 key购买 nike

假设我有一个看起来像这样的表 Orders

|country| customer_id | order_id |
| CA | 5 | 3 |
| CA | 5 | 4 |
| CA | 6 | 5 |
| CA | 6 | 6 |
| US | 2 | 7 |
| US | 7 | 8 |
| US | 7 | 9 |
| US | 7 | 10 |
| US | 2 | 11 |

我想写一个查询来填充一个表,

| country | customers_w_2_orders | customers_w_2_plus_orders |
| CA | 2 | 0 |
| US | 1 | 1 |

它按国家/地区聚合有 2 个订单的客户数量和有 3 个订单的客户数量。

这是我所做的,但没有给出我想要的结果..

SELECT country, count(*) as cnt1, count(*) as cnt2 
FROM Orders
GROUP BY country
HAVING cnt1=2 AND cnt2>2;

最佳答案

declare @orders table (country char(2), customer_id int, order_id int);
insert into @orders values
('CA', 5, 3),
('CA', 5, 4),
('CA', 6, 5),
('CA', 6, 6),
('US', 2, 7),
('US', 7, 8),
('US', 7, 9),
('US', 7, 10),
('US', 2, 11);

select country,
sum(case when num_orders <= 2 then 1 else 0 end) as cust_w_2_orders,
sum(case when num_orders > 2 then 1 else 0 end) as cust_2_plus_orders
from (
select country, customer_id, count(*) num_orders
from @orders
group by country, customer_id
) x
group by country;
GO
country | cust_w_2_orders | cust_2_plus_orders:------ | --------------: | -----------------:CA      |               2 |                  0US      |               1 |                  1

dbfiddle here

关于mysql - SQL - 通过不同的条件聚合相同的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43011146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com