我想知道是否有可能出现这样的情况:
((CASE WHEN (a = 1 AND b = 1) OR c = 0 THEN xyz ELSE 0))
我可以看到很多带有AND的CASE,但是没有OR。
还有一件事是需要像
这样的SELECT查询Select x,y,z, SUM(( CASE WHEN .....))
来自表格。
任何帮助将不胜感激
CREATE PROCEDURE abc
@sid int
AS
BEGIN
SELECT
Column1,
Column2,
Column3,
SUM((CASE WHEN ((a = 1 AND b != 0 ) OR (c = 720)) THEN Amount ELSE 0 END))
AS total
FROM view
WHERE sid = @sid
END
答案 0 :(得分:0)
我无法对此进行测试,但您需要的是以下内容。可能有一种更智能的写法。
SELECT
Column1,
Column2,
Column3,
SUM(NewAmount) AS TOTAL
FROM
SELECT
Column1,
Column2,
Column3,
CASE
WHEN (a = 1 AND b != 0 ) OR c = 720 THEN Amount
ELSE 0
END
AS NewAmount
FROM
view
GROUP BY
Column1,
Column2,
Column3
答案 1 :(得分:0)
这应该有效:
Select
Column1,
Column2,
Column3,
Sum(
Case
When ( ( a = 1 ) And ( b != 0 ) ) Or ( c = 720 ) Then Amount
Else 0
End
) As total
From
view
Where
sid = ...
Group By
Column1, Column2, Column3
如果a,b和c是数字。
答案 2 :(得分:0)
如果你想要可读的解决方案,你可以避免使用多个语句和很多圆括号。
CASE WHEN A OR B OR C THEN amount
ELSE 0
END
<=>
CASE WHEN A THEN amount -- this condition will be evalued first
WHEN B THEN amount -- second
WHEN C THEN amount -- and third
ELSE 0
END
在你的情况下:
CREATE PROCEDURE abc
@sid int
AS
BEGIN
SELECT
Column1,
Column2,
Column3,
[total] = SUM(CASE
WHEN c = 720 THEN Amount
WHEN a = 1 AND b != 0 THEN Amount
ELSE 0
END)
FROM view
WHERE sid = @sid
GROUP BY Column1, Column2, Column3
END
请注意,您需要将GROUP BY
用于未包含聚合函数的列。
<小时/> 我将使用user defined table valued function而不是存储过程的第二件事:
CREATE FUNCTION [dbo].[abc](@sid int)
RETURNS TABLE
AS
RETURN (
SELECT
Column1,
Column2,
Column3,
[total] = SUM(CASE
WHEN c = 720 THEN Amount
WHEN a = 1 AND b != 0 THEN Amount
ELSE 0
END)
FROM view
WHERE sid = @sid
GROUP BY Column1, Column2, Column3
);
然后我可以用resultset做任何我想做的事情:
SELECT *
FROM [dbo].[abc](1)
WHERE Column1 = 'xxx'