需要SQL查询的帮助

时间:2009-12-13 12:34:39

标签: sql-server-2005 tsql

SELECT @Tax = SUM(QuoteItem.SalesPrice) * TOP (1) Tax.Amount 
FROM Tax INNER JOIN
      Job ON Tax.TaxId = Job.TaxId INNER JOIN
      Quote ON Job.JobId = Quote.JobId INNER JOIN
      QuoteItem INNER JOIN
      Room ON QuoteItem.RoomId = Room.RoomId ON Quote.QuoteId = Room.QuoteId
WHERE (Room.QuoteId = @QuoteId) AND (QuoteItem.UnitId = @UnitId)
    RETURN @Tax

结果:

Msg 156, Level 15, State 1, Procedure fn_GetQuoteUnitTax, Line 54
Incorrect syntax near the keyword 'TOP'.

注意,当我省略TOP(1)时,它说:

Msg 8120, Level 16, State 1, Procedure fn_GetQuoteUnitTax, Line 54
Column 'Tax.Amount' is invalid in the select list because it is not contained in
either an aggregate function or the GROUP BY clause.

2 个答案:

答案 0 :(得分:0)

我认为您需要在两个单独的查询中执行此操作。第一个获得税额:

select @tax = Tax.Amount
  from Tax
    inner join ...whatever else you need here...
  where ...

请注意,在设置@tax变量值时不能使用'top'子句 - 您需要在where子句中执行一些操作来选择所需的值。

然后获得销售价格:

select @sales = sum(QuoteItem.SalesPrice
  from ...
  where ...

最后返回结果:

return @tax * @sales

答案 1 :(得分:0)

根据http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=137110

SELECT @Tax = SUM(QuoteItem.SalesPrice * Tax.Amount)