您可以請協助分割日期結果集到sql server中的列
我有一個查詢,顯示教師的數量,訪問的網站以及他們訪問的日期。該查詢查看過去一週的所有教師訪問情況。
我想將dateattended字段拆分爲列以顯示過去一週的每日訪問。下面是它的外觀。
EmployeeNumber Name HomeSite Site Attended Day Attended
TP-000322789 Samuel Mohlamnyane Teacher Port Elizabeth 2014-10-18 07:23
TP-000148774 Jean Smoothie Teacher Hennopsview 2014-10-13 08:55
TP-000148774 Jean Smoothie Teacher Hennopsview 2014-10-16 08:43
TP-000148122 Anthony Mike Teacher Tzaneen 2014-10-19 09:19
TP-000148122 Anthony Mike Teacher Tzaneen 2014-10-15 08:26
TP-000328452 Geneve Gorridon Teacher Tzaneen 2014-10-14 07:44
TP-000346529 Edmos Dube Teacher Melrose 2014-10-18 07:47
TP-000321374 Anita Rene Classen Teacher Johannesburg 2014-10-17 07:57
TP-000324511 Anthonysia White Teacher Durbanville 2014-10-15 07:53
TP-000324511 Anthonysia White Teacher Durbanville 2014-10-18 12:26
TP-000327471 Moses Mathebula Teacher Polokwane 2014-10-13 05:50
TP-000148194 Nonhlanhla Ndlovu Teacher Vereeniging 2014-10-15 07:06
TP-000323383 Lerato Manyanka Teacher Bedfordview 2014-10-13 07:26
TP-000323383 Lerato Manyanka Teacher Bedfordview 2014-10-16 06:51
TP-000323384 Lerato Manyanka Teacher Bedfordview 2014-10-17 08:57
現在我想拆分日出席日期不同列從昨天走到過去七天。
下面是我用來獲得上述結果集的代碼。結果應該如何。
EmployeeNumber Name HomeSite Site Attended Day 1 Day2 Day 3 Day 4 Day 5 Day 6 Day 7
TP-000148194 Nonhlanhla Ndlovu Teacher Vereeniging 2014-10-15 07:06
TP-000323383 Lerato Manyanka Teacher Bedfordview 2014-10-17 08:57 2014-10-16 06:51 2014-10-13 07:26
SELECT mdet.MemRefNo AS 'EmployeeNumber'
, cont.FirstName + ' ' + cont.LastName AS Name
, s.Name AS 'HomeSite'
, Attend.VisitedSite AS 'Site Attended'
, Attend.Weekdays AS 'Day Attended'
FROM MemberDetail mdet
INNER JOIN MembershipHistory mhis ON mdet.CurrentMembershipID = mhis.ID32
INNER JOIN contacts cont ON cont.GUID = mdet.ContactGUID
INNER JOIN Sites s ON s.id = cont.HomeSiteID
INNER JOIN Packages pg ON pg.ID = mhis.PackageID
CROSS APPLY
(
SELECT min(a1.attenddate) AS Weekdays , a1.contactguid, a1.SiteID , s.Name as VisitedSite FROM dbo.attendance a1
INNER JOIN Sites s ON s.id = a1.Siteid
WHERE DATEDIFF(DAY,a1.attenddate,GETDATE()) <= 7
and ContactGuid = mdet.ContactGuid
AND a1.isswipesuccessful = 1
GROUP BY a1.ContactGuid, DATEPART(DW, a1.attenddate),a1.SiteID , s.Name
) Attend
WHERE pg.Description LIKE '%Teacher%'
您可以編輯的問題增加的新列應該是什麼樣子的例子嗎? – acfrancis 2014-10-20 15:10:45
嗨,我已編輯上述查詢,以顯示這應該看起來如何 – user1538257 2014-10-21 06:29:39
好,所以你已經寫了一個選擇。它產生你想要的結果嗎?它靠近嗎? – acfrancis 2014-10-21 09:11:15