如何获取列记录sql中两个日期之间的天数

时间:2017-04-20 08:55:04

标签: mysql sql

我有一个表partywise_account_ledger,其中包含name_of_the_customerinvoice_dateinvoice_value列。我想根据天数检索invoice_value。要获取< 5 days的值,我使用查询:

select name_of_the_customer, sum(invoice_value)
from partywise_accounts_ledger
where datediff(d, invoice_date, '2017-04-19') < 5
group by name_of_the_customer 

This is the Result of the Query

如何将< 10 days列附加到其中并在单个语句中显示?

谢谢!

1 个答案:

答案 0 :(得分:1)

case表达式用于条件聚合:

select name_of_the_customer,
       sum(case when datediff(d, invoice_date, '2017-04-19') < 5 then invoice_value end),
       sum(case when datediff(d, invoice_date, '2017-04-19') < 10 then invoice_value end)
from partywise_accounts_ledger
where datediff(d, invoice_date, '2017-04-19') < 10
group by name_of_the_customer

第二个SUM()(适用于<10天),可以简化为sum(invoice_value)