SQL如何仅从MIN值中减去

时间:2018-05-15 11:28:53

标签: sql-server-2016

我的查询非常简单:

SELECT SUM(rate), SUM(nights), SUM(rate) * SUM(nights) AS subtotal, (SUM(rate) * SUM(nights)) * MIN(tax) AS tax,
   SUM(adults), SUM(fee), ((SUM(rate) * SUM(nights)) * MIN(tax)) + SUM(fee) AS total
    FROM table
        WHERE group = @group_code
            GROUP BY rate

我的查询结果:

rate   nights   subtotal      tax     adults     fee      total
  0.00   14         0.00      0.00       21      105      105.00
154.00  226     34804.00   5373.04      141      705    40882.04
254.00    6      1524.00    235.27        4       20     1779.27

我希望能够从MIN(速率)行中减去2个成年人,在这种情况下,行的结果为$ 0.00,但保留其他行。

任何人都可以提供帮助吗?

1 个答案:

答案 0 :(得分:1)

如果我理解得恰到好处,那就可以了:

with s as (
    select
        SUM(rate) rate,
        SUM(nights) nights,
        SUM(rate) * SUM(nights) subtotal,
        (SUM(rate) * SUM(nights)) * MIN(tax) tax,
        SUM(adults) adults,
        SUM(fee) fee,
        ((SUM(rate) * SUM(nights)) * MIN(tax)) + SUM(fee) total,
    from table
    where group = @group_code
    group by rate
), sorted as (
    select s.rate, s.nights, s.subtotal, s.tax, s.adults, s.fee, s.total, ROW_NUMBER() over(order by s.rate) lp
    from s
)
select sorted.rate,
    sorted.nights,
    sorted.subtotal,
    sorted.tax,
    sorted.adults + IIF(lp = 1, -2, 0),
    sorted.fee,
    sorted.total
from sorted