[英]How to split month in first 10 days, next 10 days, and remaining days of a month in SQL
該查詢將在SQL中按月和年分組。 我想對此用戶進行選擇查詢,用戶將在其中輸入FromDate
和ToDate
:
我正在測試的查詢:
select
year(CDate) as Payment_year,
count(distinct CDate) as count_days,
month(CDate) as month_name,
isnull(sum(Amount),0.00) as Total_Amount
from
tblCowMilk
where
CDate between '2016-01-01' and '2016-03-31'
group by
year(CDate),
month(CDate),
(datepart(day,CDate))/11
order by
month_name
我想要這樣的結果
Payment Register for the Period: 01-05-2015 to 23-02-2016
-----------------------------------------------------------------------------------------
MONTH days I PERIOD days II PERIOD day III PERIOD TOTAL
-----------------------------------------------------------------------------------------
May 10 10.00 10 160.00 11 0.00 170.00
June 30.00 0.00 0.00 30.00
July 20.00 0.00 10.00 30.00
August 0.00 0.00 0.00 0.00
September 10.00 0.00 0.00 10.00
October 0.00 0.00 0.00 0.00
November 0.00 0.00 0.00 0.00
December 0.00 0.00 0.00 0.00
January 0.00 0.00 0.00 0.00
February 0.00 0.00 0.00 0.00
-----------------------------------------------------------------------------------------
70.00 160.00 10.00 240.00
-----------------------------------------------------------------------------------------
您計算10天小組的邏輯是錯誤的,目前
1-10
11-21
22-end of month
這應該返回正確的結果:
select
year(CDate) as Payment_year,
count(* as count_days,
month(CDate) as month_name,
sum(case when period = 1 then Total_Amount else 0 end) as Period_I,
sum(case when period = 2 then Total_Amount else 0 end) as Period_II,
sum(case when period = 3 then Total_Amount else 0 end) as Period_III,
isnull(sum(Total_Amount),0.00) as Total_Amount
from
(
select
CDate,
case -- 10 days within a period
when datepart(day,CDate) <= 10 then 1
when datepart(day,CDate) <= 20 then 3
else 3
end as period,
sum(Amount) as Total_Amount
from
tblCowMilk
where
CDate between '2016-01-01' and '2016-03-31'
group by
CDate,
case
when datepart(day,CDate) <= 10 then 1
when datepart(day,CDate) <= 20 then 3
else 3
end
) as dt
group by year(CDate), month(CDate)
order by year(CDate), month(CDate)
要獲得總計,您需要標准SQL的擴展分組,我不知道SQL Server 2012是否完全支持此功能:
group by
grouping sets ((year(CDate),month(CDate)),())
order by
grouping(year(CDate)), year(CDate),
grouping(month(CDate)), month(CDate)
或者在您的應用程序中完成總計。
嘗試這個
select
year(a.CDate) as Payment_year,
month(a.CDate) as month_name,
COUNT(b.Amount) as 'I Period',
COUNT(c.Amount) as 'II Period',
COUNT(d.Amount) as 'II Period',
isnull(sum(a.Amount),0.00) as Total_Amount
from
tblCowMilk a
left join tblCowMilk d on d.CDate = a.CDate and DAY(d.CDate) < 11
left join tblCowMilk b on b.CDate = a.CDate and DAY(b.CDate) >10 and DAY(b.CDate) <21
left join tblCowMilk c on c.CDate = a.CDate and DAY(c.CDate) >20
where
a.CDate between '2016-01-01' and '2016-03-31'
group by
year(a.CDate),
month(a.CDate),
order by
month_name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.