下面的查詢:
SELECT appointment.[CustomerID]
,appointment.[Date]
,appointment.[Status]
,(SELECT COUNT(*) FROM [CustomerAppointment] as arrived
WHERE arrived.CustomerID = appointment.CustomerID
AND arrived.Date < appointment.Date
AND arrived.Status = 'Arrived') as [ArrivedSum]
,(SELECT COUNT(*) FROM [CustomerAppointment] as arrived
WHERE arrived.CustomerID = appointment.CustomerID
AND arrived.Date < appointment.Date
AND arrived.Status = 'Canceled') as [CanceledSum]
,(SELECT COUNT(*) FROM [CustomerAppointment] as arrived
WHERE arrived.CustomerID = appointment.CustomerID
AND arrived.Date < appointment.Date
AND arrived.Status = 'Not Arrived') as [NotArrivedSum]
,(SELECT COUNT(*) FROM [CustomerAppointment] as arrived
WHERE arrived.CustomerID = appointment.CustomerID
AND arrived.Date < appointment.Date) as [TotalAppointments]
,CASE WHEN (SELECT COUNT(*) FROM [CustomerAppointment] as arrived
WHERE arrived.CustomerID = appointment.CustomerID
AND arrived.Date < appointment.Date) = 0 THEN 'First' ELSE appointment.[Status] END as [LastApptStatus]
FROM [dbo].[CustomerAppointment] as appointment
GROUP BY appointment.[CustomerID],appointment.[Date],appointment.[Status]
會給你你正在等待結果。
另外,我建議你使用技術主鍵,以避免從計算中忘記相同的客戶ID /日期的條目。一個簡單的IDENTITY將會很好。
隨着PK的查詢會是這樣:
SELECT appointment.[CustomerID]
,appointment.[Date]
,appointment.[Status]
,(SELECT COUNT(*) FROM [CustomerAppointment] as arrived
WHERE arrived.CustomerID = appointment.CustomerID
AND arrived.myPK < appointment.myPK
AND arrived.Status = 'Arrived') as [ArrivedSum]
,(SELECT COUNT(*) FROM [CustomerAppointment] as arrived
WHERE arrived.CustomerID = appointment.CustomerID
AND arrived.myPK < appointment.myPK
AND arrived.Status = 'Canceled') as [CanceledSum]
,(SELECT COUNT(*) FROM [CustomerAppointment] as arrived
WHERE arrived.CustomerID = appointment.CustomerID
AND arrived.myPK < appointment.myPK
AND arrived.Status = 'Not Arrived') as [NotArrivedSum]
,(SELECT COUNT(*) FROM [CustomerAppointment] as arrived
WHERE arrived.CustomerID = appointment.CustomerID
AND arrived.myPK < appointment.myPK) as [TotalAppointments]
,CASE WHEN (SELECT COUNT(*) FROM [CustomerAppointment] as arrived
WHERE arrived.CustomerID = appointment.CustomerID
AND arrived.myPK < appointment.myPK) = 0 THEN 'First' ELSE appointment.[Status] END as [LastApptStatus]
FROM [dbo].[CustomerAppointment] as appointment
GROUP BY appointment.[CustomerID],appointment.[Date],appointment.[Status]
請仔細閱讀http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of- code-on-so-when-asking-question-285557和接受的答案 –
我正在使用MSSQL ...並感謝您分享鏈接和信息。 – Tmike21