我正在尝试显示每个用户在本周花费时间做的事情(内部或外部工作),但时间全部在表格的同一列上,是否可以将其拆分为2个不同的列和仍然拥有它,以便它只显示每个用户一次,而不是每次他们输入的时间,这可能是整个星期多次。
下面的SQL为我提供了每个用户一周的跟踪时间,但不同行的内部和外部跟踪时间。
SELECT SUM(FilteredMag_Time.mag_hoursspent) AS Time,
FilteredSystemUser.fullname,
FilteredMag_project.mag_typename
FROM FilteredSystemUser
INNER JOIN FilteredMag_Task
INNER JOIN FilteredMag_project ON FilteredMag_Task.mag_projectid = FilteredMag_project.mag_projectid
INNER JOIN FilteredMag_Time ON FilteredMag_Task.mag_taskid = FilteredMag_Time.mag_taskid
ON FilteredSystemUser.systemuserid = FilteredMag_Time.createdby
WHERE (FilteredMag_Time.mag_starttime BETWEEN DATEADD(dd, - (DATEPART(dw, GETDATE()) - 1), GETDATE())
AND DATEADD(dd, - (DATEPART(dw, GETDATE()) - 7), GETDATE()))
GROUP BY FilteredSystemUser.fullname, FilteredMag_project.mag_typename
ORDER BY FilteredSystemUser.fullname
以下是当前输出的示例。
Time fullname mag_typename
------------------ --------------------- -------------------------
1.2500000000 David Sutton External
8.2500000000 Gayan Perera External
9.0000000000 Paul Nieuwelaar Internal
14.8700000000 Roshan Mehta External
6.0000000000 Roshan Mehta Internal
2.7800000000 Simon Phillips External
4.6600000000 Simon Phillips Internal
答案 0 :(得分:1)
您可以使用SQL Server PIVOT。
像
这样的东西DECLARE @Table TABLE(
userID INT,
typeID VARCHAR(20),
TimeSpent FLOAT
)
INSERT INTO @Table SELECT 1, 'INTERNAL', 1
INSERT INTO @Table SELECT 2, 'INTERNAL', 1
INSERT INTO @Table SELECT 1, 'INTERNAL', 1
INSERT INTO @Table SELECT 1, 'INTERNAL', 1
INSERT INTO @Table SELECT 2, 'EXTERNAL', 3
INSERT INTO @Table SELECT 1, 'EXTERNAL', 3
SELECT *
FROM
(
SELECT userID, typeID, TimeSpent
FROM @Table
) s
PIVOT (SUM(TimeSpent) FOR typeID IN ([INTERNAL],[EXTERNAL])) pvt
输出:
userID INTERNAL EXTERNAL
----------- ---------------------- ----------------------
1 3 3
2 1 3
答案 1 :(得分:0)
假设FilteredMag_project.mag_typename
为“内部”或“外部”,请尝试以下操作:
SELECT SUM(CASE FilteredMag_project.mag_typename
WHEN 'INTERNAL' THEN FilteredMag_Time.mag_hoursspent
ELSE 0 END) AS InternalTime,
SUM(CASE FilteredMag_project.mag_typename
WHEN 'EXTERNAL' THEN FilteredMag_Time.mag_hoursspent
ELSE 0 END) AS ExternalTime,
FilteredSystemUser.fullname
FROM FilteredSystemUser
INNER JOIN FilteredMag_Task
INNER JOIN FilteredMag_project ON FilteredMag_Task.mag_projectid = FilteredMag_project.mag_projectid
INNER JOIN FilteredMag_Time ON FilteredMag_Task.mag_taskid = FilteredMag_Time.mag_taskid
ON FilteredSystemUser.systemuserid = FilteredMag_Time.createdby
WHERE (FilteredMag_Time.mag_starttime BETWEEN DATEADD(dd, - (DATEPART(dw, GETDATE()) - 1), GETDATE())
AND DATEADD(dd, - (DATEPART(dw, GETDATE()) - 7), GETDATE()))
GROUP BY FilteredSystemUser.fullname
ORDER BY FilteredSystemUser.fullname