假设我们有表:
+----------+------------+
| order_id | order_type |
+----------+------------+
| 1 | classsic |
+----------+------------+
| 2 | classic |
+----------+------------+
| 3 | urgent |
+----------+------------+
| 4 | urgent |
+----------+------------+
| 5 | canceled |
+----------+------------+
| 6 | canceled |
+----------+------------+
| 7 | classic |
+----------+------------+
并要求获取所有订单的总数以及每个order_type的订单数。
返回的结果应该类似于:
+-------+---------+--------+----------+
| total | classic | urgent | canceled |
+-------+---------+--------+----------+
| 7 | 3 | 2 | 2 |
+-------+---------+--------+----------+
哪个sql语句会得到我们上面的结果?
答案 0 :(得分:3)
使用条件聚合
select count(*) total,
count(case when order_type = 'classic' then 1 end) classic,
count(case when order_type = 'urgent ' then 1 end) urgent ,
count(case when order_type = 'canceled ' then 1 end) canceled
from your_table
答案 1 :(得分:2)
这将执行所需的输出。有关PIVOT
运营商here
declare @tbl as table(
order_id int
,order_type varchar(15)
)
insert into @tbl values (1, 'classic')
insert into @tbl values (2, 'classic')
insert into @tbl values (3, 'urgent')
insert into @tbl values (4, 'urgent')
insert into @tbl values (5, 'canceled')
insert into @tbl values (6, 'canceled')
insert into @tbl values (7, 'classic')
SELECT
classic + urgent + canceled AS Total
,classic
,urgent
,canceled
FROM (
SELECT order_id, order_type from @tbl
) tbl
PIVOT(
COUNT(order_id) FOR order_type IN (classic, urgent, canceled)
) pvt
答案 2 :(得分:2)
如果您不想Case
或Dynamic
,请使用Pivot
表达式的另一种方法:
SELECT COUNT(*) total,
SUM(CASE
WHEN order_type = 'classic'
OR order_type = 'classsic'
THEN 1
ELSE 0
END) classic,
SUM(CASE
WHEN order_type = ' urgent '
THEN 1
ELSE 0
END) urgent,
SUM(CASE
WHEN order_type = 'canceled'
THEN 1
ELSE 0
END) canceled
FROM <table_name>;
结果:
+-------+---------+--------+----------+
| total | classic | urgent | canceled |
+-------+---------+--------+----------+
| 7 | 3 | 2 | 2 |
+-------+---------+--------+----------+