聚合函数导致select语句

时间:2017-10-21 08:29:32

标签: sql sql-server tsql azure-sql-database

希望下面的代码能说明我想要实现的目标。

问题在于,当我尝试计算VatableCash时,没有任何输入选择被解析,因此在尝试选择时会出现“无效列”。

对不起,如果我能在这里做一些明显的事情。 SQL不是我的强项之一。

select
    OrderHeader.ID,
    sum(OrderLine.NetPrice) as OrderLineNetPrice,
    sum(OrderLine.GrossPrice) as OrderLineGrossPrice,
    sum(
        case when PaymentOption_ID = 8
            then Payment.Amount
            else 0
        end
    ) as TotalCashAmount,
    ((OrderLineGrossPrice - OrderLineNetPrice) / OrderLineGrossPrice) * TotalCashAmount as VatableCash
    from OrderHeader
    inner join Payment on Payment.OrderHeader_ID = OrderHeader.ID
    inner join OrderLine on OrderLine.OrderHeader_ID = OrderHeader.ID
    group by OrderHeader.ID

2 个答案:

答案 0 :(得分:2)

您需要使用子查询。

你可以试试这个。

;WITH CTE AS
(
    select
        OrderHeader.ID,
        sum(OrderLine.NetPrice) as OrderLineNetPrice,
        sum(OrderLine.GrossPrice) as OrderLineGrossPrice,
        sum(
            case when PaymentOption_ID = 8
                then Payment.Amount
                else 0
            end
        ) as TotalCashAmount
    from OrderHeader
        inner join Payment on Payment.OrderHeader_ID = OrderHeader.ID
        inner join OrderLine on OrderLine.OrderHeader_ID = OrderHeader.ID
    group by OrderHeader.ID
)
SELECT *, 
    ((OrderLineGrossPrice - OrderLineNetPrice) / OrderLineGrossPrice) * TotalCashAmount as VatableCash
FROM CTE

答案 1 :(得分:2)

爱十字架申请!只要你想要一些方便的额外列,就可以使用它。

select
    OrderHeader.ID,
    sum(OrderLine.NetPrice) as OrderLineNetPrice,
    sum(OrderLine.GrossPrice) as OrderLineGrossPrice,
    TotalCashAmount,
    ((OrderLineGrossPrice - OrderLineNetPrice) / OrderLineGrossPrice) * TotalCashAmount as VatableCash
    from OrderHeader
    inner join Payment on Payment.OrderHeader_ID = OrderHeader.ID
    inner join OrderLine on OrderLine.OrderHeader_ID = OrderHeader.ID
    cross apply ( select sum(
        case when PaymentOption_ID = 8
            then Payment.Amount
            else 0
        end
    )) as subquery(TotalCashAmount)
    group by OrderHeader.ID