SQL 如何将数据分组到单独的月份列中
SQL How to group data into separate month columns
所以我 运行 这个查询是为了获取客户的姓名、订购的总金额以及他们提交的订单数量。通过这个查询,我得到了他们从三月到七月的整个历史,我想要的是名称,三月总金额/订单数量,四月总金额/订单数量,可能总金额/订单数量,.....等等
SELECT customer_name,MONTH(created_on), SUM(amount), COUNT(order_id)
FROM customer_orders
WHERE created_on BETWEEN '2020-03-01' AND '2020-08-01'
GROUP BY customer_name, MONTH(created_on)
如果您想要单独的 列 中的值,则使用条件聚合:
SELECT customer_name,
SUM(CASE WHEN MONTH(created_on) = 3 THEN amount END) as march_amount,
SUM(CASE WHEN MONTH(created_on) = 3 THEN 1 ELSE 0 END) as march_count,
SUM(CASE WHEN MONTH(created_on) = 4 THEN amount END) as april_amount,
SUM(CASE WHEN MONTH(created_on) = 4 THEN 1 ELSE 0 END) as april_count,
. . .
FROM customer_orders
WHERE created_on >= '2020-03-01' AND
created_on < '2020-08-01'
GROUP BY customer_name;
请注意,我更改了日期过滤器,因此它不包括 2020-08-01。
所以我 运行 这个查询是为了获取客户的姓名、订购的总金额以及他们提交的订单数量。通过这个查询,我得到了他们从三月到七月的整个历史,我想要的是名称,三月总金额/订单数量,四月总金额/订单数量,可能总金额/订单数量,.....等等
SELECT customer_name,MONTH(created_on), SUM(amount), COUNT(order_id)
FROM customer_orders
WHERE created_on BETWEEN '2020-03-01' AND '2020-08-01'
GROUP BY customer_name, MONTH(created_on)
如果您想要单独的 列 中的值,则使用条件聚合:
SELECT customer_name,
SUM(CASE WHEN MONTH(created_on) = 3 THEN amount END) as march_amount,
SUM(CASE WHEN MONTH(created_on) = 3 THEN 1 ELSE 0 END) as march_count,
SUM(CASE WHEN MONTH(created_on) = 4 THEN amount END) as april_amount,
SUM(CASE WHEN MONTH(created_on) = 4 THEN 1 ELSE 0 END) as april_count,
. . .
FROM customer_orders
WHERE created_on >= '2020-03-01' AND
created_on < '2020-08-01'
GROUP BY customer_name;
请注意,我更改了日期过滤器,因此它不包括 2020-08-01。