2014-11-20 91 views
0

我有下面的聯合查詢,它通過15個級別;我只顯示三個,所以你明白了。我想爲輸入設置頂部的變量,所以我不需要每次都更改15x3條件。變量我想在頂部設置一次應用到所有有: pyh_per_cc pyh_tc_batch pyh_no01(注:這是一個「IN」的標準)爲聯合查詢設置變量

有沒有辦法做到這一點?我正在使用SQL Server Mgmt Studio 2008 R2以防有所作爲。 在此先感謝!

select hr_pe_id, pyh_no01 pyh_no, pyh_amt01 pyh_amt 
from pyh_hst_dtl 
where pyh_no01 <> 0 
and pyh_per_cc = '1301001' 
and pyh_tc_batch = 'P1301001' 
and pyh_no01 in ('2100','2101','2105','2108','2113','2115','2117','2118','2119') 
union 
select hr_pe_id, pyh_no02 pyh_no, pyh_amt02 pyh_amt 
from pyh_hst_dtl 
where pyh_no02 <> 0 
and pyh_per_cc = '1301001' 
and pyh_tc_batch = 'P1301001' 
and pyh_no02 in ('2100','2101','2105','2108','2113','2115','2117','2118','2119') 
union 
select hr_pe_id, pyh_no03 pyh_no, pyh_amt03 pyh_amt 
from pyh_hst_dtl 
where pyh_no03 <> 0 
and pyh_per_cc = '1301001' 
and pyh_tc_batch = 'P1301001' 
and pyh_no03 in ('2100','2101','2105','2108','2113','2115','2117','2118','2119') 
order by hr_pe_id 
+0

使用臨時「內存表」可能/值得嗎?這是'不支點'嗎? – 2014-11-20 21:40:16

+0

不確定什麼是'不可調整的'是...? – Jenn 2014-11-20 22:25:30

+0

UNPIVOT通過將列旋轉爲行來執行幾乎反向操作的PIVOT。那是我認爲你正在嘗試做的事情? [標準T-SQL-逆轉置(http://www.ingenioussql.com/2013/05/09/standard-t-sql-unpivot/)。使用'過程語言'在數據庫之外執行操作有時更容易 – 2014-11-20 22:37:17

回答

0

對不起,錯過了你正在測試同一個字段的值兩次。

會這樣嗎?

CREATE TABLE #pyh_nos(pyh_no char(4)); 

insert into #pyh_nos values ('2100'); 
insert into #pyh_nos values ('2101'); 
insert into #pyh_nos values ('2105'); 
insert into #pyh_nos values ('2108'); 
insert into #pyh_nos values ('2113'); 
insert into #pyh_nos values ('2115'); 
insert into #pyh_nos values ('2117'); 
insert into #pyh_nos values ('2118'); 
insert into #pyh_nos values ('2119'); 

select 
hr_pe_id, pyh_no01 pyh_no, pyh_amt01 pyh_amt 
from 
pyh_hst_dtl h left outer join 
#pyh_nos p1 on 
pyh_no01 = p1.pyh_no left outer join 
#pyh_nos p2 on 
pyh_no02 = p2.pyh_no 
... 
left outer join 
#pyh_nos p15 on 
pyh_no15 = p15.pyh_no 
where 
pyh_per_cc = '1301001' 
and pyh_tc_batch = 'P1301001' and 
(p1.pyh_no is not null or 
... 
p15.pyh_no is not null) 
+0

優秀的觀察。這正是OP需要簡化查詢的方式。 – paqogomez 2014-11-20 21:42:07

+0

這個查詢是不一樣的。問題中列出的每個級別都會查看不同字段的值,而不是總是pyh_no01,但是pyh_no02和pyh_no03 – 2014-11-20 21:43:18

+0

?此查詢還查找15個不同字段中的值 – Beth 2014-11-20 21:44:57