选择2个类似记录中的1个而不是

时间:2015-02-26 16:14:29

标签: sql-server tsql

所以我有一张叫做“请求”的表格。存储假期请求。我想尝试使用clocknumber的参数从表中(与其他人一起)提取某些记录。但是,如果有两个记录具有相同的HolidayID且最后一个(前1个desc)具有特定值 - 我们不会在select中包含该记录!

请求表[缩短版本];

http://i.stack.imgur.com/YY1Gk.png

使用的存储过程传递了用户名的参数,并加入了其他三个表,

  • a'假期' table(存储来自等的假日信息)
  • a'用户'表(包含用户名等)
  • a' RequestType' table(包含请求类型)

从表格的图像中,如果您想象所有这些请求都属于同一个用户,我只想提取请求类型为1的记录。(请求类型1是假日请求,2是假日取消) 。但是,如果有第二条记录具有相同的holidayID且请求类型为2,则不包括该记录。

所以运行查询,我想只获取ID为1和2的记录,因为最后2个具有相同的假日ID,而2中的最后一个具有取消假期的请求类型。

这是我尝试过的查询;

SELECT Holidays.ID, EmployeeClockNumber, Employees.Name AS EmployeeName, HolidayStart, HolidayEnd, HalfDay, AMPM
FROM Holidays
INNER JOIN Employees ON Employees.ClockNumber = Holidays.EmployeeClockNumber
INNER JOIN Requests ON Requests.HolidayID = Holidays.ID
WHERE EmployeeClockNumber = @ClockNo 
AND Requests.Accepted = 1
AND RequestTypeID = (SELECT TOP 1 Requests.ID 
                    FROM Requests 
                    INNER JOIN Holidays ON Holidays.ID = Requests.HolidayID
                    WHERE Requests.RequestTypeID = (SELECT ID FROM RequestType WHERE RequestType = 'Holiday Request') 
                    AND Holidays.EmployeeClockNumber = @ClockNo
                    ORDER BY Requests.ID DESC)
ORDER BY ID DESC

有人能指出我正确的方向吗?谢谢

编辑:我自己开始工作了!

SELECT Holidays.ID, Holidays.EmployeeClockNumber, Employees.Name AS EmployeeName, Holidays.HolidayStart, Holidays.HolidayEnd, Holidays.HalfDay, Holidays.AMPM
FROM Requests 
INNER JOIN Holidays ON Holidays.ID = Requests.HolidayID
INNER JOIN Employees ON Employees.ClockNumber = Holidays.EmployeeClockNumber
WHERE Holidays.EmployeeClockNumber = @ClockNo
AND Requests.Accepted = 1
AND Requests.HolidayID NOT IN (SELECT TOP 1 HolidayID
                                FROM Requests AS R1
                                WHERE R1.RequestTypeID <> (SELECT ID FROM RequestType WHERE RequestType = 'Holiday Request')
                                AND R1.HolidayID = Requests.HolidayID 
                                ORDER BY R1.ID DESC)

2 个答案:

答案 0 :(得分:0)

我会在select上使用分区,然后对其进行过滤。

类似

DECLARE @mtable TABLE (
    ID INT
    ,RequestTypeId INT
    ,HolidayId INT
    ,Accepted NVARCHAR(50)
)


INSERT @mtable VALUES (1,1,1,'True')
INSERT @mtable VALUES (2,1,2,'True')
INSERT @mtable VALUES (3,1,3,'True')
INSERT @mtable VALUES (4,2,3,'True')


SELECT * FROM (
SELECT MAX(RequestTypeId) OVER (PARTITION BY HolidayID) AS MaxType
,Id
FROM @mtable
) q 
WHERE q.MaxType <> 2

答案 1 :(得分:0)

SELECT * FROM TAB WHERE requestTypeID  = 1
AND holidayID not in (SELECT HolidayID from TAB WHERE requestTypeID  = 2)