gpt4 book ai didi

sql - 聚合多个条件 : convert to a single query

转载 作者:行者123 更新时间:2023-11-29 12:33:58 25 4
gpt4 key购买 nike

给定表格:

预订(id、place_id、confirmed_at、paid_at)地方(id,名字)

我需要返回可以分别表示以下查询的聚合:

-- Confirmed
SELECT places.id, places.name, COUNT(reservations.*) as total_confirmed
FROM reservations
INNER JOIN places ON places.id = reservations.place_id
WHERE
reservations.confirmed_at IS NOT NULL
GROUP BY places.id, places.name

-- Paid
SELECT places.id, places.name, COUNT(reservations.*) as total_paid
FROM reservations
INNER JOIN places ON places.id = reservations.place_id
WHERE
reservations.paid_at IS NOT NULL
GROUP BY places.id, places.name

-- Paid Uncofirmed
SELECT places.id, places.name, COUNT(reservations.*) as total_paid_unconfirmed
FROM reservations
INNER JOIN places ON places.id = reservations.place_id
WHERE
reservations.paid_at IS NOT NULL AND reservations.confirmed_at IS NULL
GROUP BY places.id, places.name

如何将这些查询重写为一个查询并返回所有必要的?

最佳答案

SELECT places.id, places.name,
sum(case when (reservations.confirmed_at IS NOT NULL) then 1 else 0 end) as total_confirmed,
sum(case when (reservations.paid_at IS NOT NULL) then 1 else 0 end) as total_paid,
sum(case when (reservations.paid_at IS NOT NULL AND reservations.confirmed_at IS NULL) then 1 else 0 end) as total_confirmed_paid
FROM reservations
INNER JOIN places ON places.id = reservations.place_id
GROUP BY places.id, places.name

关于sql - 聚合多个条件 : convert to a single query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12742659/

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