我想问一下是否可以创建一个if或类似结构的SQL语句。 我有两个查询,并希望将它们合并为一个。两者之间的唯一区别是,在WHERE子句中有一个额外的AND条件。 我尝试做一个选择案例,但不是很成功。我将创建一个参数“test”,它将占用1或2,并且该条件应该确定要运行的查询。 以下是查询...
查询1
SELECT ID,AVG(B.VOL) AS PVOL
FROM (SELECT VAR1 AS ID, SUM(VOL) AS PVOL FROM table1 WHERE VAR1='xyz'
AND DATE_D>'10/28/2013' AND DATE_D<'10/31/2013'
AND CUSTOMER='Market' AND MARKET='South' AND PROJECT=0
GROUP BY VAR1,DATE_D) B GROUP BY ID
查询2
SELECT ID,AVG(B.VOL) AS PVOL
FROM (SELECT VAR1 AS ID, SUM(VOL) AS PVOL FROM table1 WHERE VAR1='xyz'
AND DATE_D>'10/28/2013' AND DATE_D<'10/31/2013'
AND PROJECT=0
GROUP BY VAR1,DATE_D) B GROUP BY ID
答案 0 :(得分:1)
您可以根据参数@test添加条件,如下所示 可以使用相同的查询,根据参数条件的变化。
SELECT ID,AVG(B.VOL) AS PVOL
FROM (SELECT VAR1 AS ID, SUM(VOL) AS PVOL FROM table1 WHERE VAR1='xyz'
AND DATE_D>'10/28/2013' AND DATE_D<'10/31/2013'
AND ( (@test = 1 AND CUSTOMER='Market' AND MARKET='South' AND PROJECT=0 )
OR ( @test =2 AND PROJECT=0 )
)
GROUP BY VAR1,DATE_D) B GROUP BY ID
答案 1 :(得分:1)
你可以创建一个接受你希望建立你的IF语句的“test”参数的sproc。
create procedure --sprocname
(
@test int
)
as
begin
set nocount on
if
@test = --bool
select statement 1
else
select statement 2
end
抱歉格式不好我急着设置