11g và cao hơn: Sử dụng listagg:
SELECT
col1,
LISTAGG(col2, ', ') WITHIN GROUP (ORDER BY col2) "names"
FROM table_x
GROUP BY col1
10g và thấp hơn: Một phương pháp là sử dụng một chức năng:
CREATE OR REPLACE FUNCTION get_comma_separated_value (input_val in number)
RETURN VARCHAR2
IS
return_text VARCHAR2(10000) := NULL;
BEGIN
FOR x IN (SELECT col2 FROM table_name WHERE col1 = input_val) LOOP
return_text := return_text || ',' || x.col2 ;
END LOOP;
RETURN LTRIM(return_text, ',');
END;
/
Để sử dụng chức năng:
select col1, get_comma_separated_value(col1) from table_name
Lưu ý: Có chức năng (không được hỗ trợ) WM_CONCAT
khả dụng trên một số phiên bản cũ hơn của Oracle, có thể giúp bạn thực hiện - xem here for details.
Trong MySQL:
SELECT col1, GROUP_CONCAT(col2) FROM table_name GROUP BY col1
Bạn có muốn truy vấn để làm việc cả trong Oracle và MySQL? –
có thể trùng lặp của [this] (http://stackoverflow.com/questions/4686543/sql-to-concatenate-column-values-from-multiple-rows) hoặc [this] (http://stackoverflow.com/questions/1120706/is-there-an-oracle-sql-query-that-aggregates-nhiều hàng-thành-một-hàng) hoặc [this] (http://stackoverflow.com/questions/12145379/how-to- lấy-hai cột-dữ liệu-in-ab-định dạng-in-oracle) hoặc [this] (http://stackoverflow.com/questions/5822700/building-a-comma-separated-list-of-values-in -an-oracle-sql-statement) hoặc ... –