如何修改SQL查询以考虑此特定过滤条件?

时间:2015-08-03 06:38:33

标签: sql-server filter where

我正在使用SQL Query 2014,我对我的数据库运行了以下T-SQL查询:

use My Database

SELECT * FROM 
(
SELECT a.ReservationStayID,
       c.PMSConfirmationNumber,
       a.StayDate,
       DATEPART(MONTH,a.StayDate) AS 'Month',
       DATEPART(YEAR,a.StayDate) AS 'Year',
       c.[MTH], 
       a.PackagePlanCode,
       c.[Market Segment Code],
       c.[CurrencyCode],
       a.RateAmount,
       SUM(a.RateAmount) OVER(PARTITION BY a.ReservationStayID) AS 'CUM_Rate',
       d.[Exchange Rate],
       ((a.RateAmount * d.[Exchange Rate])/1.15) AS 'PR',
       c.[PropertyCode],
       C.[Room Nights],
       c.[Tour Operator],
       c.[Group Booking ID],
       c.[Source of Business],
       c.[Booking Origin (1)], 
       c.[Market FINAL],
       c.[CreatedOn],
       c.[CreatedOn_RSD]

FROM ReservationStayDate a

INNER JOIN 

(SELECT *

FROM [RESERVATIONLIST]) c ON c.[ReservationStayID] = a.ReservationStayID and c.[MTH] = datename(m,StayDate) + ' ' + cast(datepart(yyyy,StayDate) as varchar)

INNER JOIN 

(SELECT *

FROM [PKGREVENUE]) d ON d.[ReservationStayID] = a.ReservationStayID AND d.[StayDate] = a.StayDate

WHERE c.[Status] <> 'CANCELED'
) q

WHERE q.CUM_Rate <> 0 

ORDER BY q.ReservationStayID, q.StayDate

以上查询运行正常但现在我想要包含一个过滤器,其中输出中包含以下ReservationStayID152, 167, 658, 900

这些ReservationStayID都有CUM_Rate = 0,这意味着它们会自动排除在现有查询的输出中。

我尝试过以下但是没有用:

WHERE (q.CUM_Rate <> 0 AND q.ReservationStayId IN (152, 167, 658, 900))

如何添加此特定条件?

1 个答案:

答案 0 :(得分:0)

以下为ReservationStayID 152167658900未出现在您的结果中的原因:

  1. RESERVATIONLISTWHERE STATUS <> 'CANCELED'
  2. 上没有行
  3. PKGREVENUE
  4. 上没有匹配的行

    要解决您的问题,您可能需要将INNER JOIN转换为LEFT JOIN。此外,您可能希望在CASE子句中使用SUM() OVER表达式。而不是在AND子句中使用WHERE,而应使用OR

    SELECT * FROM (
        SELECT 
            --...,
            SUM(CASE 
                    WHEN c.[Status] <> 'CANCELLED' THEN a.RateAmount
                    ELSE 0
                END
                ) OVER(PARTITION BY a.ReservationStayID) AS 'CUM_Rate',
            --...
        FROM ReservationStayDate a
        LEFT  JOIN RESERVATIONLIST c    
            ON c.[ReservationStayID] = a.ReservationStayID 
            AND c.[MTH] = DATENAME(M, StayDate) + ' ' + CAST(DATEPART(YYYY,StayDate) AS VARCHAR)
            AND c.[Status] <> 'CANCELED'
        LEFT JOIN PKGREVENUEd 
            ON d.[ReservationStayID] = a.ReservationStayID
            AND d.[StayDate] = a.StayDate   
    ) q
    WHERE 
        q.CUM_Rate <> 0
        OR q.ReservationStayId IN (152, 167, 658, 900)
    ORDER BY q.ReservationStayID, q.StayDate
    

    注意:我更改了部分JOIN以直接使用该表,而不是使用子查询和SELECT * FROM <table>