这是我的疑问:
SELECT claims.id,
COUNT(CASE WHEN claims.sold_at BETWEEN (now() - INTERVAL '7.day') AND now() END FROM claims) week1
FROM users
LEFT JOIN claims ON claims.sales_user_id = users.id
WHERE users.office_id = 2
我要做的是加入索赔表,然后计算在特定日期期间售出的数量
此查询出错,但不确定如何正确修复/接近它?
答案 0 :(得分:1)
试试这个:
select
users.id, count(claims.id) as count
from users
left join claims on claims.sales_user_id = users.id
where
users.office_id = 2 and
claims.sold_at between (current_timestamp - interval '7' day) and current_timestamp
group by users.id;
答案 1 :(得分:0)
您的查询应如下所示
SELECT claims.id,
COUNT(CASE
WHEN claims.sold_at BETWEEN (now() - INTERVAL '7.day') AND now()
THEN claims.id
ELSE null END) week1
FROM users
LEFT JOIN claims ON claims.sales_user_id = users.id
WHERE users.office_id = 2
答案 2 :(得分:0)
select
users.id,
count(
claims.sold_at between (now() - interval '7.day') and now()
or null
) week1
from
users
left join
claims on claims.sales_user_id = users.id
where users.office_id = 2
group by users.id
答案 3 :(得分:0)
通常对于这种事情你使用SUM(IF())。
这样的事情: -
SELECT claims.id,
SUM(IF(claims.sold_at BETWEEN DATE_SUB(now(), INTERVAL 7 DAY) AND now(), 1, 0)) AS week1
FROM users
LEFT JOIN claims ON claims.sales_user_id = users.id
WHERE users.office_id = 2
但这本身就没有意义。为什么要将claim.id带回来?没有GROUP BY子句的聚合函数意味着只返回一行,因此返回的claims.id将是随机的。但我希望id是唯一的密钥,所以在这种情况下,它的分组似乎是错误的。