我正在使用SQL Server 2014,我有以下运行正常的T-SQL查询并提供以下输出:
SELECT a.StayID,
a.StayDate,
a.PlanCode,
c.[Currency],
a.Rate,
d.[ROE],
c.[Property],
c.[Tour]
FROM ResStay a
INNER JOIN
(SELECT *
FROM [LIST]) c ON c.[StayID] = a.StayID and c.[MTH] = datename(m,StayDate) + ' ' + cast(datepart(yyyy,StayDate) as varchar)
INNER JOIN
(SELECT *
FROM [PKGREVENUE]) d ON d.[StayID] = a.StayID AND d.[StayDate] = a.StayDate
WHERE c.[Status] <> 'CANCELED'
AND a.[StayDate] >= '2015-07-01'
ORDER BY a.StayID, a.StayDate
当前输出如下:
StayID StayDate PlanCode Cuurency Rate ROE Property Tour
152 2015-07-01 G1HB GBP 102 56 ASD Smith
152 2015-07-02 G1HB GBP 102 56 ASD Smith
152 2015-07-03 G1HB GBP 102 56 ASD Smith
178 2015-09-11 COAI GBP 0 48 ASD Jones
178 2015-09-12 DEAI GBP 115 48 ASD Jones
189 2015-10-02 COHB GBP 0 56 ASD Thomson
189 2015-10-03 COHB GBP 0 56 ASD Thomson
189 2015-10-04 COHB GBP 0 56 ASD Thomson
我需要在查询中添加一个过滤器,以便它排除所有StayID,其Sum的速率等于0。
因此我需要修改我的查询以便输出以下内容:
StayID StayDate PlanCode Cuurency Rate ROE Property Tour
152 2015-07-01 G1HB GBP 102 56 ASD Smith
152 2015-07-02 G1HB GBP 102 56 ASD Smith
152 2015-07-03 G1HB GBP 102 56 ASD Smith
178 2015-09-11 COAI GBP 0 48 ASD Jones
178 2015-09-12 DEAI GBP 115 48 ASD Jones
答案 0 :(得分:0)
添加cum_rate列并对其进行过滤。
SELECT q.StayID, q.StayDate, q.PlanCode, q.Currency, q.Rate, q.ROE, q.Property, q.Tour FROM
(SELECT a.StayID,
a.StayDate,
a.PlanCode,
c.[Currency],
a.Rate,
SUM(a.RATE) OVER(PARTITION BY StayID) as CUM_RATE,
d.[ROE],
c.[Property],
c.[Tour]
FROM ResStay a
INNER JOIN
[LIST] c ON c.[StayID] = a.StayID and c.[MTH] = datename(m,StayDate) + ' ' + cast(datepart(yyyy,StayDate) as varchar)
INNER JOIN
[PKGREVENUE] d ON d.[StayID] = a.StayID AND d.[StayDate] = a.StayDate
WHERE c.[Status] <> 'CANCELED'
AND a.[StayDate] >= '2015-07-01'
)q
WHERE q.CUM_RATE >0
ORDER BY q.ReservationStayID, q.StayDate
答案 1 :(得分:0)
要总结您的费率,您需要使用汇总函数SUM
,并使用StayDate的Max
函数来获得一个包含费率总和的stayID。以下是如何做到这一点:
SELECT a.StayID AS ReservationStayID
,max(a.StayDate)
,a.PlanCode
,c.[Currency]
,SUM(a.Rate) AS Rate
,d.[ROE]
,c.[Property]
,c.[Tour]
FROM ResStay a
INNER JOIN [LIST] c ON c.[StayID] = a.StayID
AND c.[MTH] = datename(m, StayDate) + ' ' + cast(datepart(yyyy, StayDate) AS VARCHAR)
INNER JOIN [PKGREVENUE] d ON d.[StayID] = a.StayID
AND d.[StayDate] = a.StayDate
WHERE c.[Status] <> 'CANCELED'
AND a.[StayDate] >= '2015-07-01'
GROUP BY a.stayID
,a.PlanCode
,c.Currency
,d.ROE
,c.Property
,c.Tour
HAVING SUM(a.Rate) > 0
ORDER BY a.StayID
注意:我删除了联接中的select语句,因为这不需要。您可以直接加入表格而无需选择。所以,我希望你也不要介意我改变它。