我对SQL很新,所以请耐心等待。 我有一个表(DataTable),其中包含日期列(日期)和计数列(计数)
我需要创建一个新表来计算:计数,运行总计,运行财务年度,运行12个月。然后将这些全部添加到一个列中,并添加一个新的类别列,将这些总和分隔为“月份”,“合同到日期”,“财政年度”和#39;和#12个月结束月份#。
结果将是
如何在一个查询中编写所有这些(无需创建4个单独的表) 我需要使用SQL Server Management Studio 2008或2008r2 据我所知,研究:
SELECT * INTO DataTableFinal FROM (
SELECT Date, Count
FROM DataTable
UNION All
SELECT Date, Count = Sum (Count) OVER (ORDER BY Date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM DataTable
UNION All
SELECT Date, Count =
FROM DataTable
UNION All
SELECT Date, Count =
FROM DataTable
) as tmp
答案 0 :(得分:2)
我不认为sql server 2008在窗口函数中支持sum()
order by
。试试这样的事情
SELECT dates,[Count],'MOnth'
FROM Yourtable
UNION ALL
SELECT dates,run,'Contract to Date'
FROM Yourtable a
CROSS apply (SELECT Sum([Count])
FROM Yourtable b
WHERE a.dates >= b.dates) cs (run)
答案 1 :(得分:0)
最终结果:
SELECT dates,[Count],'Month'
FROM Yourtable
UNION ALL
SELECT dates,cnt,'Contract to Date'
FROM Yourtable a
CROSS apply (SELECT Sum([Count])
FROM Yourtable b
WHERE a.dates >= b.dates) cs (cnt)
UNION ALL
SELECT dates,cnt,'12 Months to End Date'
FROM Yourtable a
CROSS apply (SELECT Sum([Count])
FROM Yourtable b
WHERE a.dates >= b.dates and b.dates >= DATEADD(month, -12, a.dates)) cs (cnt)
UNION ALL
SELECT dates,cnt,'Financial Year'
FROM Yourtable a
CROSS apply (SELECT Sum([Count])
FROM Yourtable b
WHERE a.dates >= b.dates and b.dates >= DATEADD(year,DATEDIFF(month,'19100701',a.dates)/12,'19100701')) cs (cnt)