# 與where子句相矛盾的問題

SELECT SUM(FilteredMag_Time.mag_hoursspent) AS Time,
FilteredSystemUser.fullname,
FilteredMag_project.mag_typename
FROM FilteredSystemUser
INNER JOIN FilteredMag_project ON FilteredMag_Task.mag_projectid = FilteredMag_project.mag_projectid
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


## 最佳答案

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