뭔가 어리석은 실수를 하고 있는 것은 분명하지만, 도대체 무슨 실수인지 알 수가 없습니다:
SQL Server 2005에서 오전 2시 이전에 예약한 고객을 제외한 모든 고객을 선택하려고 합니다.
이 쿼리를 실행하면
SELECT idCustomer FROM reservations
WHERE idCustomer NOT IN
(SELECT distinct idCustomer FROM reservations
WHERE DATEPART ( hour, insertDate) < 2)
결과가 0개입니다.
하지만
SELECT idCustomer FROM reservations
는 152.000개의 결과와 'NOT IN' 부분을 반환합니다:
SELECT distinct idCustomer FROM reservations
WHERE DATEPART ( hour, insertDate) < 2
는 284개 행만 반환합니다.
SELECT distinct idCustomer FROM reservations
WHERE DATEPART ( hour, insertDate) < 2
and idCustomer is not null
목록 매개변수에 널 값이 포함되어 있지 않은지 확인하세요.
여기에 설명이 있습니다:
WHERE field1 NOT IN (1, 2, 3, null)
와 동일합니다:
WHERE NOT (field1 = 1 OR field1 = 2 OR field1 = 3 OR field1 = null)
(*) 편집: 이 설명은 꽤 훌륭하지만, 향후의 오해의 소지를 없애기 위해 한 가지를 언급하고 싶습니다. (TRUE 또는 NULL)은 TRUE로 평가됩니다. 예를 들어 field1 = 3인 경우에 해당됩니다. 이 TRUE 값은 FALSE로 부정되고 행이 필터링됩니다.
IF 1 NOT IN (1, 2, 3, NULL) PRINT '1 NOT IN (1, 2, 3, NULL)'
IF 1 NOT IN (2, 3, NULL) PRINT '1 NOT IN (2, 3, NULL)'
IF 1 NOT IN (2, 3) PRINT '1 NOT IN (2, 3)' -- Prints
IF 1 IN (1, 2, 3, NULL) PRINT '1 IN (1, 2, 3, NULL)' -- Prints
IF 1 IN (2, 3, NULL) PRINT '1 IN (2, 3, NULL)'
IF 1 IN (2, 3) PRINT '1 IN (2, 3)'
SELECT Reservations.idCustomer FROM Reservations (nolock)
LEFT OUTER JOIN @reservations ExcludedReservations (nolock) ON Reservations.idCustomer=ExcludedReservations.idCustomer AND DATEPART(hour, ExcludedReservations.insertDate) < 2
WHERE ExcludedReservations.idCustomer IS NULL AND Reservations.idCustomer IS NOT NULL
GROUP BY Reservations.idCustomer
[업데이트: 원래 게시자의 주요 문제였던 idCustomer가 NULL인 경우 처리하는 추가 기준을 추가했습니다.]
SELECT MIN(A.maxsal) secondhigh
FROM (
SELECT TOP 2 MAX(EmployeeBasic) maxsal
FROM M_Salary
GROUP BY EmployeeBasic
ORDER BY EmployeeBasic DESC
) A