将两个查询与不同的地方合并为1

时间:2014-09-19 13:06:31

标签: sql tsql stored-procedures

我有一个存储过程如下。

DECLARE @Temp TABLE
(...)

INSERT INTO @Temp
SELECT  MeasureDate, col1, col2
FROM Table1
WHERE Col3 = 1

INSERT INTO @Temp
SELECT  MeasureDate, col1, col2
FROM Table1
WHERE Col3 = 1
AND Col4 = 7000

SELECT SUM(col1) / SUM(col2) AS Percentage, MAX(), MeasureDate
FROM @Temp
GROUP BY MeasureDate

我在临时表中进行了两次插入,第二次插入有一个额外的WHERE但是同一列相同的表,然后我在临时表上执行SUM(col1)/ SUM(col2)以返回我需要的结果。有没有办法合并所有这些插入并选择一个语句所以我不使用临时表并从表1中进行一次选择?或者即使我仍然需要临时表,将选择合并为一个选择而不是两个单独的选择?存储过程工作正常,只是寻找缩短它的方法。

感谢。

2 个答案:

答案 0 :(得分:2)

SELECT  MeasureDate, col1, col2
FROM Table1
WHERE Col3 = 2
  or (Col3 = 1 AND Col4 = 7000);


SELECT  sum(col1) / sum(col2) AS Percentage , GROUP BY MeasureDate
FROM Table1
WHERE Col3 = 2
  or (Col3 = 1 AND Col4 = 7000)
GROUP BY MeasureDate;

答案 1 :(得分:1)

您可以将前两个查询中的条件与or运算符组合在一起:

SELECT   SUM(col1) / SUM(col2) AS Percentage, MeasureDate
FROM     Table1
WHERE    (Col3 = 2) OR (Col3 = 1 AND Col4 = 7000)
GROUP BY MeasureDate