2011-08-17 17 views
2

這裏的問題:SQL查詢從行轉移值列的子查詢組

數據集是:

Col1  Col2 
BK.01.04 A0103 
BK.01.04 A0306 
BK.01.04 A0309 
BK.01.04 A0403 
BK.02.01 A1403 
BK.02.02 A1403 
BK.02.03 A0403 
BK.02.03 A0703 
BK.02.04 A0103 
BK.02.04 A0306 
BK.02.04 A0309 
BK.02.04 A0403 

所需要的結果是:

Col1  Col2 Col3 Col4 Col5 
BK.01.04 A0103 A0306 A0309 A0403 
BK.02.01 A1403 
BK.02.02 A1403 
BK.02.04 A0103 A0306 A0309 A0403 

如何任何想法在MS Access/Plain SQL中執行此操作?任何幫助是極大的讚賞:)

+0

我想像這必須是一個動態的解決方案,因爲該數據可能會改變,你不能保證每個記錄'Col1'值數可能有? – Yuck

回答

0

加入表回自己:

select 
    t1.col1, 
    t1.col2, 
    t2.col2 as col3, 
    t3.col2 as col4, 
    t4.col2 as col5 
from mytable t1 
left join mytable t2 on t2.col1 = t1.col1 and t2.col2 > t1.col2 
left join mytable t3 on t3.col1 = t1.col1 and t3.col2 > t2.col2 and t2.col2 is not null 
left join mytable t4 on t4.col1 = t1.col1 and t4.col2 > t3.col2 and t3.col2 is not null 
order by 1; 

使用left join意味着你會得到空白時所加入的表中沒有匹配的行。連接條件中的所有廢話都是爲了確保每列中有不同的和遞增的值。

+0

這將返回20行,而不是僅僅5 ... –

0

不完全正是你想要的,但我認爲你會發現將最左邊的列填充爲值使用ANSI-SQL想...

透視表:

CREATE TABLE DataSet (Col1 varchar(20), Col2 varchar(20)) 

INSERT INTO DataSet (Col1, Col2) VALUES ('BK.01.04','A0103') 
INSERT INTO DataSet (Col1, Col2) VALUES ('BK.01.04','A0306') 
INSERT INTO DataSet (Col1, Col2) VALUES ('BK.01.04','A0309') 
INSERT INTO DataSet (Col1, Col2) VALUES ('BK.01.04','A0403') 
INSERT INTO DataSet (Col1, Col2) VALUES ('BK.02.01','A1403') 
INSERT INTO DataSet (Col1, Col2) VALUES ('BK.02.02','A1403') 
INSERT INTO DataSet (Col1, Col2) VALUES ('BK.02.03','A0403') 
INSERT INTO DataSet (Col1, Col2) VALUES ('BK.02.03','A0703') 
INSERT INTO DataSet (Col1, Col2) VALUES ('BK.02.04','A0103') 
INSERT INTO DataSet (Col1, Col2) VALUES ('BK.02.04','A0306') 
INSERT INTO DataSet (Col1, Col2) VALUES ('BK.02.04','A0309') 
INSERT INTO DataSet (Col1, Col2) VALUES ('BK.02.04','A0403') 

SELECT Col1, 
MAX(CASE Col2 WHEN 'A0103' THEN 'A0103' ELSE '' END) Col2, 
MAX(CASE Col2 WHEN 'A0306' THEN 'A0306' ELSE '' END) Col3, 
MAX(CASE Col2 WHEN 'A0309' THEN 'A0309' ELSE '' END) Col4, 
MAX(CASE Col2 WHEN 'A0403' THEN 'A0403' ELSE '' END) Col5, 
MAX(CASE Col2 WHEN 'A1403' THEN 'A1403' ELSE '' END) Col6 
FROM DataSet 
GROUP BY DataSet.Col1 

結果:

Col1     Col2 Col3 Col4 Col5 Col6 
-------------------- ----- ----- ----- ----- ----- 
BK.01.04    A0103 A0306 A0309 A0403 
BK.02.01          A1403 
BK.02.02          A1403 
BK.02.03        A0403 
BK.02.04    A0103 A0306 A0309 A0403 

(5 row(s) affected) 

如果您正在使用MS-Access,可以accompl通過使用樞軸表十歲上下同樣的事情:

http://office.microsoft.com/en-us/access-help/designing-your-first-pivottable-pivotchart-views-in-access-HA001034580.aspx

+1

不知道,但可能這不會在MS Access中(因爲CASE,我認爲,這不支持那裏)。 –

+0

如果您使用的是MS Access,則可以使用內置的透視功能動態地完成相同的操作。 –