我正在使用mysql,必须在不同的三种情况下从db表中归档一个
my db table user_pay
fields- username,amt,postingDate,category
我想要类似的结果
username amtbeforedate amtbetweendate amtcategory
john 500 1000 1200
每个字段的条件
where conditions- startdate, enddate, category
username
amtbeforedate= sum(amt) From user_pay WHERE postingDate > startdate
amtbetweendate=sum(amt) From user_pay WHERE postingDate BETWEEN startdate AND enddate AND (category='paid' OR category='notpaid')
amtcategory =sum(amt) From user_pay WHERE postingDate BETWEEN startdate AND enddate AND (category='adjustment')
我希望此结果在单个查询中。 我尝试不同的示例,但没有任何结果 查询只会被调用一次,而不是每行一次
答案 0 :(得分:0)
如果我理解您提出的问题是正确的,您可以在总和内应用条件 像这样的东西
SUM(CASE WHEN postingDate > startdate THEN amt ELSE 0 END) as amtbeforedate
整个查询都是这样
select
SUM(CASE WHEN postingDate > startdate THEN amt ELSE 0 END) as amtbeforedate
SUM(CASE WHEN postingDate BETWEEN startdate AND enddate AND (category='paid' OR category='notpaid')
THEN amt ELSE 0 END) as amtbetweendate
SUM(CASE WHEN postingDate BETWEEN startdate AND enddate AND (category='adjustment') THEN amt ELSE 0 END) as amtbeforedate
from user_pay
希望对您有帮助