2012-01-04 108 views
-2

我想從Oracle DB中的表中進行選擇。sql選擇表的多個列

如果我在單列上的select語句中做出了明顯的改進,但對於多列而言,這似乎不起作用。例如

select DISTINCT col1, col2, col3, col4, col5, col6 from table1 

返回相同的結果。

select * from table1 

第2列第3列具有重複值。我想要的是所有上述列值的值,但不是column2和column3的重複值。

您能否請幫助。您的幫助將不勝感激。

謝謝

+1

你可以給出一個表中的內容嗎?如果你得到與SELECT *相同的結果,那麼COL1中的所有記錄都是不同的。 – ProfessionalAmateur 2012-01-04 22:08:16

+0

你想檢查[這個問題](http://stackoverflow.com/questions/54418/how-do-i-or-can-i-select-distinct-on-multiple-columns-postgresql)?看起來非常相似 – 2012-01-04 22:09:04

+3

請記住,DISTINCT應用於您要返回的整個列集,而不僅僅是第一列。因此,例如'(1,2,3,4,5,6)'與[(1,2,3,4,5,7)'不同),因爲第六列在兩行之間是不同的。 – 2012-01-04 22:10:21

回答

5

DISTINCT消除每行和所選列的冗餘數據。因此,如果使用DISTINCT選擇表的所有列,則只有包含完全相同數據的行纔會彙總。

+0

謝謝克里斯的迴應。 – Nomad 2012-01-04 22:15:18

+0

感謝您的回答。我已更新我的問題如何解決問題? – Nomad 2012-01-05 00:56:11

+0

請不要編輯問題。否則,這成爲一個聊天或留言板;)只需打開一個新的,花一些時間描述你的問題與數據樣本等。 – Chris 2012-01-05 09:14:26

1

嘗試以下操作:

SELECT DISTINCT COL1 AS COL1, NULL AS COL2, NULL AS COL3, NULL AS COL4, 
     NULL AS COL5, NULL AS COL6 FROM TABLE1 
UNION ALL 
SELECT NULL AS COL1, DCOL2 AS COL2, NULL AS COL3, NULL AS COL4, 
     NULL AS COL5, NULL AS COL6 FROM (SELECT DISTINCT COL2 AS DCOL2 
              FROM TABLE1) 
UNION ALL 
SELECT NULL AS COL1, NULL AS COL2, DCOL3 AS COL3, NULL AS COL4, 
     NULL AS COL5, NULL AS COL6 FROM (SELECT DISTINCT COL3 AS DCOL3 
              FROM TABLE1) 
UNION ALL 
SELECT NULL AS COL1, NULL AS COL2, NULL AS COL3, DCOL4 AS COL4, 
     NULL AS COL5, NULL AS COL6 FROM (SELECT DISTINCT COL4 AS DCOL4 
              FROM TABLE1) 
UNION ALL 
SELECT NULL AS COL1, NULL AS COL2, NULL AS COL3, NULL AS COL4, 
     DCOL5 AS COL5, NULL AS COL6 FROM (SELECT DISTINCT COL5 AS DCOL5 
              FROM TABLE1) 
UNION ALL 
SELECT NULL AS COL1, NULL AS COL2, NULL AS COL3, NULL AS COL4, 
     NULL AS COL5, DCOL6 AS COL6 FROM (SELECT DISTINCT COL6 AS DCOL6 
              FROM TABLE1); 

分享和享受。