ID | Date | Status | Physician ID
44397479 10/13/2009 17:40 NOSHOW
44397480 10/13/2009 16:40 CHECKED OUT 108
44397481 10/13/2009 14:32 CHECKED OUT 108
44397482 10/14/2009 10:44 RESCHEDULED 108
44397483 8/26/2009 12:35 RESCHEDULED 108
44397484 10/13/2009 15:26 CHECKED OUT 108
56084463 10/10/2009 10:00 PENDING 108
56287658 10/14/2009 10:44 PENDING 108
54728032 10/13/2009 15:56 CHECKED OUT 108
这是包含数百万条记录的表格中的示例。
我需要编写一个查询,它将计算满足以下条件的任何两行:
RESCHEDULED
,另一行为PENDING
我想显示两行,每个医生只显示一行(在SUM
函数中)。
如何使用SQL实现这一目标?
答案 0 :(得分:0)
这应该可以帮助您朝着正确的方向前进。 (完整示例)。现在,您应该能够根据需要进行分组,并总结 Dups 字段。
DECLARE @Table TABLE(
ID INT,
[Date] DATETIME,
[Status] VARCHAR(100),
[Physician ID] INT
)
INSERT INTO @Table SELECT 44397479,'10/13/2009 17:40','NOSHOW' , NULL
INSERT INTO @Table SELECT 44397480,'10/13/2009 16:40','CHECKED OUT' ,108
INSERT INTO @Table SELECT 44397481,'10/13/2009 14:32','CHECKED OUT' ,108
INSERT INTO @Table SELECT 44397482,'10/14/2009 10:44','RESCHEDULED' ,108
INSERT INTO @Table SELECT 44397483,'8/26/2009 12:35','RESCHEDULED' ,108
INSERT INTO @Table SELECT 44397484,'10/13/2009 15:26','CHECKED OUT' ,108
INSERT INTO @Table SELECT 56084463,'10/10/2009 10:00','PENDING' ,108
INSERT INTO @Table SELECT 56287658,'10/14/2009 10:44','PENDING' ,108
INSERT INTO @Table SELECT 54728032,'10/13/2009 15:56','CHECKED OUT' ,108
SELECT *,
CASE
WHEN t.[Status] = 'PENDING'
AND EXISTS(
SELECT *
FROM @Table
WHERE DATEPART(hh, [Date]) = DATEPART(hh, t.[Date])
AND DATEPART(MI, [Date]) = DATEPART(MI, t.[Date])
AND ID <> t.ID)
AND [Physician ID] = t.[Physician ID]
AND Status = 'RESCHEDULED'
THEN 0
ELSE 1
END Dups
FROM @Table t
答案 1 :(得分:0)
select t1.[Physician ID], count(*) as Count
from @Table t1
inner join @Table t2 on (
t1.date - cast(t1.date as int) = t2.date - cast(t2.date as int)
and t1.Status = 'RESCHEDULED' and t2.Status = 'PENDING'
and t1.[Physician ID] = t2.[Physician ID]
)
group by t1.[Physician ID]