我已经决定发布新主题,因为我遇到了报告,需要列出客户的发货量,总收入,现在需求略有变化(再次),我需要锻炼客户与我们交易多少个月在2015年和2016年在我们的数据库中发布/找到的第一张发票上。 例如,
-----------------------------------------------------------------
|Client code | invoice date | Number of months |
-----------------------------------------------------------------
|CliID 007 | 20161001| 1|
|CliID 012 | 20160824| 3|
-----------------------------------------------------------------
我当前的脚本检索客户和发票日期,但现在(我感到困惑)必须弄清楚如何计算在15和16之间发出第一张发票的日期之间的月数。
以下是我最终的脚本。
select
cli.code,
(Select min(invoice.dfac)
from invoice
inner join client on client.clientid = invoice.clientid
where client.bur = 'nlams'
and invoice.dfac >= '20160101'
and invoice.dfac <= '20161231'
and cli.code = client.code)
from
client as cli
where
cli.bur = 'nlams'
group by
cli.Code
任何帮助都将受到高度赞赏!
答案 0 :(得分:2)
试试这个
SELECT cli.code, MIN(invoice.dfac) firstMonth,
DATEDIFF(month, MIN(invoice.dfac), GETDATE()) MonthsPassed
FROM client AS cli
LEFT JOIN invoice ON client.clientid = invoice.clientid
WHERE client.bur = 'nlams'
GROUP BY cli.Code
答案 1 :(得分:0)
要获得月份差异的数字,请使用DATEDIFF,以便SELECT部分变为:
Select DATEDIFF(m, MIN(invoice.dfac), GETDATE())