[英]Various Summarized Dates in One Table or View - SQL Server v14
我正在使用SQL Server v14,并尝试创建摘要视图或表(我是SQL新手,所以请放轻松)。 我已经附上了一些示例数据,我想从这些数据创建具有以下各列(如下)的另一个表。
我无法将一个以上的日期字段汇总到一个表中,因为“ where”语句只能捕获其中之一。 如何在表格中创建多个汇总列? 如何为每一列创建多个WHERE字段?
数据列标题示例(输入)
USID| Job_Desc| Grouping Designation| hoursdate| hours
USBUGBY None DIRECT 1/21/2019 5
US76546 None DIRECT 12/31/2018 6
US76546 None DIRECT 12/31/2018 6
US73546 None CTE 2/28/2019 6
US73546 None CTE 2/28/2019 6
所需输出:
USID MTD Hours Rolling Hours Current Month Hours
列逻辑
将多个汇总轻松放入不同列的方法是使用子查询。 例如:
DECLARE @dt date
SET @dt = '20190201' -- Easiest if this is set to the 1st of the current month
-- Otherwise, calculate the 1st of month.
SELECT
USID
(
SELECT Sum(hours)
FROM MyTable mt
WHERE mt.HoursDate >= DATEADD(Month, -1, @dt)
AND mt.HoursDate < @dt
AND mt.USID = m.USID
) Prior_MTD_Hours, -- Prior Month, so if today is 2/1 it should show January
(
SELECT Sum(hours)
FROM MyTable mt
WHERE HoursDate >= DATEADD(Month, -12, @dt)
AND HoursDate < @dt
AND mt.USID = m.USID
) Rolling Hours, --12 month to Prior Month
(
SELECT Sum(hours)
FROM MyTable mt
WHERE HoursDate >= @dt
AND HoursDate < Dateadd(Month, 1, @dt)
AND mt.USID = m.USID
) Current Month Hours, -- Current Month (so if today is 1/21, this would be all of January)
(
SELECT Sum(hours)
FROM MyTable mt
WHERE HoursDate >= DATEADD(Month, 1, @dt)
AND HoursDate < Dateadd(Month, 2, @dt)
AND mt.USID = m.USID
) Next Month Hours
FROM MyTable m
这是您要寻找的基本框架。 显然,您还将需要的任何其他分组添加到内部查询中。
还有其他方法也可以完成,例如使用子查询作为派生表:
SELECT ...
FROM Mytable m
LEFT JOIN (
SELECT USID, Sum(hours) as PriorMthHrs
FROM MyTable mt
WHERE mt.HoursDate >= DATEADD(Month, -1, @dt)
AND mt.HoursDate < @dt
GROUP BY USID
) as mp
ON mp.USID = m.usid
LEFT JOIN (
SELECT USID, Sum(hours)
FROM MyTable mt
WHERE HoursDate >= DATEADD(Month, -12, @dt)
AND HoursDate < @dt
AND mt.USID = m.USID
GROUP BY USID
) as mr
ON mr.USID = m.usid
....
这些示例片段应为您提供执行此操作所需的基本格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.