2016-08-23 86 views
0

我有一個查詢,像這樣:的Oracle SQL逗號分隔的ID

SELECT 
    s.id, 
    CASE 
    WHEN INSTR(s.strain_value, '[') = 0 
    THEN s.strain_name 
    ELSE TRIM(SUBSTR(s.strain_name, 1, INSTR(s.strain_name, '[')-1)) 
    END AS strain_name 
FROM strain s 

這給了我一個表,看起來像:

id  strain_name 
---------------------------------------------- 
100  CD-1 
101  CD-1 
102  CD-1 
200  SCID 
300  BusIp-hy 
301  BusIp-hy 
...  ... 

現在由我strain_name想組結果表並獲得逗號分隔id像下面這樣:

id    strain_name 
---------------------------------------------- 
100, 101, 102 CD-1 
200    SCID 
300, 301  BusIp-hy 
...    ... 

我嘗試此查詢出來,但我沒有牛逼得到我想要的東西:

WITH q AS (
    SELECT 
    s.id, 
    CASE 
     WHEN INSTR(s.strain_name, '[') = 0 
     THEN s.strain_name 
     ELSE TRIM(SUBSTR(s.strain_name, 1, INSTR(s.strain_name, '[')-1)) 
    END AS strain_name 
    FROM strain s 
) 
SELECT (
    SELECT LISTAGG(id, ', ') 
    WITHIN GROUP (
    ORDER BY strain_name ASC 
) 
    FROM (SELECT DISTINCT strain_name FROM q) dc 
) AS id, strain_name 
FROM q 

能否請你幫我糾正過去的查詢,這樣我可以得到id的每個strain_name一個逗號分隔的列表?

回答

2
WITH q (id, strain_name) AS (
    SELECT id, 
     CASE WHEN INSTR(strain_value, '[') = 0 
       THEN strain_name 
       ELSE TRIM(SUBSTR(strain_name, 1, INSTR(strain_name, '[')-1)) 
     END 
    FROM strain 
) 
SELECT LISTAGG(id, ', ') WITHIN GROUP (ORDER BY id) AS id, 
     strain_name 
FROM q 
GROUP BY strain_name 
+0

感謝,這對我的作品。只是想知道爲什麼你必須將'ORDER BY'從'strain_name'改爲'id'? –

+1

@PatrickGregorio從您的預期結果看來,您希望以升序排列以逗號分隔的ID。 'LISTAGG'的'ORDER BY'在組內,因此所有的項目都有相同的'strain_name'(因爲這是group by子句) - 使用這個順序會導致[非確定性排序] (http://stackoverflow.com/q/35747417/1509264),但「id」值看起來都不一樣,因此會導致確定性排序。 – MT0

2

您是否嘗試過GROUP BY?

WITH q AS (
... 
) 
SELECT strain_name, listagg(id, ', ') within GROUP(ORDER BY id) 
FROM q 
GROUP BY strain_name 
ORDER BY strain_name 
2
WITH q AS (
    SELECT 
    s.id, 
    CASE 
     WHEN INSTR(s.strain_name, '[') = 0 
     THEN s.strain_name 
     ELSE TRIM(SUBSTR(s.strain_name, 1, INSTR(s.strain_name, '[')-1)) 
    END AS strain_name 
    FROM strain s 
) 
SELECT LISTAGG(id, ', ') WITHIN GROUP (ORDER BY id ASC) as id, q.strain_name 
    FROM q 
group by q.strain_name