3我有以下查询
SELECT deal_id, max(test_value) - min(test_value) AS deviation
FROM table
WHERE run_date >= Dateadd(month, -4, Getdate())
and test_alias='BOND_P'
group by deal_id
having (max(test_value) - min(test_value)) BETWEEN 1.79 AND 4.5
和
SELECT deal_id, max(test_value) - min(test_value) AS deviation
FROM ems.cdotests
WHERE run_date >= Dateadd(month, -3, Getdate())
and test_alias='CAA/CCC'
group by deal_id
having (max(test_value) - min(test_value)) BETWEEN 2.79 AND 2
我需要结合此查询,以便我可以将输出作为
1: result set of query 1 intersected with result set of query 2
2: result set of query 1 unioned with result set of query 2
'Intersect'或'Union'将取决于传递给存储过程的参数
Ps注意:两个查询之间的运行日期条件可以不同 任何帮助将不胜感激
答案 0 :(得分:0)
IF @myBitParameter = 0
SELECT deal_id, max(test_value) - min(test_value) AS deviation
FROM [table]
WHERE run_date >= Dateadd(month, -4, Getdate())
and test_alias='BOND_P'
group by deal_id
having (max(test_value) - min(test_value)) BETWEEN 1.79 AND 4.5
UNION ALL --or UNION, if you don't want duplicates
SELECT deal_id, max(test_value) - min(test_value) AS deviation
FROM ems.cdotests
WHERE run_date >= Dateadd(month, -3, Getdate())
and test_alias='CAA/CCC'
group by deal_id
having (max(test_value) - min(test_value)) BETWEEN 2.79 AND 2
ELSE
SELECT deal_id, max(test_value) - min(test_value) AS deviation
FROM [table]
WHERE run_date >= Dateadd(month, -4, Getdate())
and test_alias='BOND_P'
group by deal_id
having (max(test_value) - min(test_value)) BETWEEN 1.79 AND 4.5
INTERSECT
SELECT deal_id, max(test_value) - min(test_value) AS deviation
FROM ems.cdotests
WHERE run_date >= Dateadd(month, -3, Getdate())
and test_alias='CAA/CCC'
group by deal_id
having (max(test_value) - min(test_value)) BETWEEN 2.79 AND 2
我觉得应该有一种方法可以用CTE来清洁它,但是没有时间再愚弄它了。有人可以随意清理它或者从中得到更好的答案。