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

标签 mysql sql

假设我有一个看起来像这样的表 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 |                  0
US      |               1 |                  1

dbfiddle here

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

相关文章:

php yii 框架对象问题

mysql - varchar 类型列的排序依据

sql - 将日期时间变量的时间部分设置为 18 :00

mysql - 查找两个连续的日期

mysql - 我的 MySQL 程序随机运行非常慢

php - 在php中将日期格式更改为word

sql - 比较 2 个不同的数据库表列

sql - Oracle 窗口函数求和

PHP PDO - 连接过多时显示密码

javascript - 使用 jQuery Ajax 和 Mysql 生成 HTML