如何使用SQL Server 2012窗口函数来完成我的查询?

时间:2014-09-17 20:46:03

标签: sql group-by sql-server-2012 window-functions

假设我有一张维修票据表,如下所示:

Group   Ticket  Status
----------------------------
00798   299696  Open
21851   574587  Complete
21851   574588  Pending
21852   574589  Office
21866   574613  Test
21869   574617  Shipping
21870   574618  Repair
21871   574620  Open
32102   369151  Repair
43316   393920  Office
60669   433162  Office
65850   445815  Open
65999   446267  Complete
66215   446841  Repair
77818   473653  Complete
79691   477963  Office
82277   483787  Pending
86283   493697  Complete
86283   493698  Complete

我正在尝试获取状态已完成的所有故障单的列表,只要该组中的每个故障单都已完成。因此,从这个数据集中,我会得到这些票:

446267     
473653     
493697    
493698   

我不会得到574587,因为其组(21851)中有另一张票(574588)设置为待处理,未完成。

我尝试将ROW_NUMBER() OVER (PARTITION BY GroupNumber, [Status] ORDER BY GroupNumber)的变体作为子查询,但无法解决这个问题。也许它可以用group by和子查询来完成?感谢。

2 个答案:

答案 0 :(得分:1)

SQL小提琴:http://sqlfiddle.com/#!6/62ecb/2

其中任何一个都应该有效:

--get every record
select * 
from RepairTickets a
--where the status is complete
where [status] = 'Complete'
--and the status matches every...
and [status] = all 
(
    --other record's status
    select [status]
    from RepairTickets b
    --in the same group 
    where b.[Group] = a.[Group]
)

--get all records
select * 
from RepairTickets a
--where the status is complete
where [status] = 'Complete'
--where there is not
and not exists
(
    --any record
    select top 1 1
    from RepairTickets b
    --in the same group
    where b.[Group] = a.[Group]
    --but with a different status
    and b.[Status] != a.[Status]
)

注意:在上述两个方面,由于我们知道我们只是在寻找完整记录,我们可以通过将一些与内部查询相关的引用替换为[Status]来进行优化。但是上面的内容应该更容易修改,因为您只需要在一个地方声明您感兴趣的状态。

答案 1 :(得分:1)

你在想它。窗口函数不适用于所有情况。您只需计算每组中的门票数量与已完成门票的数量:

WITH tmp AS
(
    SELECT  GroupID,
            COUNT(TicketID) AS TotalTicket,
            SUM(CASE WHEN Status = 'Complete' THEN 1 ELSE 0 END) AS CompletedTicket
    FROM    Repair
    GROUP BY GroupID
)

SELECT      Repair.TicketID
FROM        tmp
INNER JOIN  Repair  ON tmp.GroupID = Repair.GroupID
WHERE       tmp.CompletedTicket = tmp.TotalTicket

(SQL Fiddle目前正在关闭,因此我无法发布)