开发者

Help with SQL CASE Statement in SELECT Query

Here is my SQL statement:

SELECT [Item], SUM([Quantity]) AS SumOfQuantity, SUM([Price Each]) AS SumOfTotal,
([SumOfTotal] / [SumOfQuantity]) As Average,
CASE 
WHEN [Average] <= 6 THEN SumOfTotal
ELSE 6*[SumOfQuantity] END AS GrossComm
FROM Data
GROUP BY [Item];

When I try to execute this query, I get the error message:

Syntax error (missing operator) in query expression 'CASE WHEN [Average] <=开发者_如何转开发 6 THEN SumOfTotal ELSE 6*[SumOfQuantity] END AS GrossComm

Any ideas?

Thanks!


You can't reference a derived field by name in the CASE statement. Instead of [average] use the formulas.

You actually may have a larger issue since all your fields are based on other derived fields, so you might have to write out the formula for each one multiple times.

It's likely there is also an issue with your other fields that the CASE is obscuring. Basically don't refer to a calculated/aliased field in the same query by name, since it won't work.

If this is SQL Server you COULD do a workaround using a CTE:

;WITH CTE AS
(
SELECT [Item], SUM([Quantity]) AS SumOfQuantity, SUM([Price Each]) AS SumOfTotal,
FROM Data
GROUP BY [Item]
)
SELECT *, ([SumOfTotal] / [SumOfQuantity]) As Average,
CASE 
WHEN  ([SumOfTotal] / [SumOfQuantity]) <= 6 THEN SumOfTotal
ELSE 6*[SumOfQuantity] END AS GrossComm
FROM CTE
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜