向查询中的两个子选择添加条件
Add condition to two sub selects in query
我有这个问题。
SELECT DISTINCT
u.email,
(
SELECT
count(DISTINCT o.id)
FROM
orders o
INNER JOIN cart_dates cd ON cd.order_id = o.id
WHERE
u.id = o.user_id
) as total,
(
SELECT
count(DISTINCT o.id)
FROM
orders o
INNER JOIN cart_dates cd ON cd.order_id = o.id AND o.pre_order = TRUE
WHERE
u.id = o.user_id
) as count
FROM
users u
如何获取行数,例如,count > (total / 2)?
我只是假设回答这个问题。
SELECT
u.email
FROM
users u
INNER JOIN cart_dates cd ON cd.order_id = o.id
GROUP BY
u.email
HAVING
COUNT(DISTINCT Case when o.pre_order = TRUE then o.id else null end) >
(COUNT(DISTINCT o.id)/2)
我试着让它更简单。
我有这个问题。
SELECT DISTINCT
u.email,
(
SELECT
count(DISTINCT o.id)
FROM
orders o
INNER JOIN cart_dates cd ON cd.order_id = o.id
WHERE
u.id = o.user_id
) as total,
(
SELECT
count(DISTINCT o.id)
FROM
orders o
INNER JOIN cart_dates cd ON cd.order_id = o.id AND o.pre_order = TRUE
WHERE
u.id = o.user_id
) as count
FROM
users u
如何获取行数,例如,count > (total / 2)?
我只是假设回答这个问题。
SELECT
u.email
FROM
users u
INNER JOIN cart_dates cd ON cd.order_id = o.id
GROUP BY
u.email
HAVING
COUNT(DISTINCT Case when o.pre_order = TRUE then o.id else null end) >
(COUNT(DISTINCT o.id)/2)
我试着让它更简单。