我想弄清楚的是如何自动计算每个月最后4个月到当月的资助日期总数。例如,因为它是六月我想要2月,3月,4月和5月的资金账户。这是我现在的编解码器,似乎无法弄明白。
DECLARE @Year int
set @Year = 2013
SELECT
d.name, a.dealer_code, b.last_name, b.city, b.state, b.phone
, COUNT(CASE WHEN MONTH(c.Funded_date) = 1 THEN 1 ELSE NULL END) January
, COUNT(CASE WHEN MONTH(c.Funded_date) = 2 THEN 1 ELSE NULL END) February
, COUNT(CASE WHEN MONTH(c.Funded_date) = 3 THEN 1 ELSE NULL END) March
, COUNT(CASE WHEN MONTH(c.Funded_date) = 4 THEN 1 ELSE NULL END) April
, COUNT(CASE WHEN MONTH(c.Funded_date) = 5 THEN 1 ELSE NULL END) May
, COUNT(CASE WHEN MONTH(c.Funded_date) = 6 THEN 1 ELSE NULL END) June
, COUNT(CASE WHEN MONTH(c.Funded_date) = 7 THEN 1 ELSE NULL END) July
, COUNT(CASE WHEN MONTH(c.Funded_date) = 8 THEN 1 ELSE NULL END) August
, COUNT(CASE WHEN MONTH(c.Funded_date) = 9 THEN 1 ELSE NULL END) September
, COUNT(CASE WHEN MONTH(c.Funded_date) = 10 THEN 1 ELSE NULL END) October
, COUNT(CASE WHEN MONTH(c.Funded_date) = 11 THEN 1 ELSE NULL END) November
, COUNT(CASE WHEN MONTH(c.Funded_date) = 12 THEN 1 ELSE NULL END) December
FROM
tdealer a
JOIN
tContact b ON a.contact_id = b.contact_id
JOIN
tContract c ON a.dealer_id = c.dealer_id
JOIN
tCompany d ON c.company_id = d.company_id
WHERE
a.dealer_code = '0003594' and YEAR(c.Funded_date) = @Year
GROUP BY
d.name,
a.dealer_code,
b.last_name,
b.city, b.state, b.phone
答案 0 :(得分:0)
如果您要弄清楚的是如何将其限制为过去4个月(并假设使用SQL Server),则可以将WHERE
条件更改为:
WHERE a.dealer_code = '0003594'
AND YEAR(c.Funded_date) = @Year
AND c.Funded_date >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-4, 0)
AND c.Funded_date < DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, 0)
答案 1 :(得分:0)
您没有提供太多信息或回复评论中的问题,这是我最好的猜测:
SELECT
d.name, a.dealer_code, b.last_name, b.city, b.state, b.phone,
MONTH(c.FundedDate),
COUNT(c.FundedDate) as RecordCount
FROM
{... same as existing ...}
WHERE
a.dealer_code = '0003594' and YEAR(c.Funded_date) = @Year
and MONTH(GETDATE()) - MONTH(c.FundedDate) between 1 and 4
GROUP BY
d.name,
a.dealer_code,
b.last_name,
b.city, b.state, b.phone,
MONTH(c.FundedDate)
答案 2 :(得分:0)
试试这个,可能有语法错误。
DECLARE @CurrentMonth int
SET @CurrentMonth = MONTH(GETDATE())
SELECT
d.name, a.dealer_code, b.last_name, b.city, b.state, b.phone
, COUNT(CASE WHEN MONTH(c.Funded_date) = @CurrentMonth THEN 1 ELSE NULL END) CurrentMonth
, COUNT(CASE WHEN MONTH(DATEADD(M,1,c.Funded_date)) = @CurrentMonth THEN 1 ELSE NULL END) PrevMonth
, COUNT(CASE WHEN MONTH(DATEADD(M,2,c.Funded_date)) = @CurrentMonth THEN 1 ELSE NULL END) CurrentMonth-2
, COUNT(CASE WHEN MONTH(DATEADD(M,3,c.Funded_date)) = @CurrentMonth THEN 1 ELSE NULL END) CurrentMonth-3
FROM
tdealer a
JOIN
tContact b ON a.contact_id = b.contact_id
JOIN
tContract c ON a.dealer_id = c.dealer_id
JOIN
tCompany d ON c.company_id = d.company_id
WHERE
a.dealer_code = '0003594' and DATEDIFF(M, c.Funded_date, GETDATE()) <= 4
GROUP BY
d.name,
a.dealer_code,
b.last_name,
b.city, b.state, b.phone