首頁 > 資料庫 > mysql教程 > 如何在SQL Server複製Oracle的LISTAGG函數?

如何在SQL Server複製Oracle的LISTAGG函數?

Susan Sarandon
發布: 2025-01-22 13:22:11
原創
791 人瀏覽過

How to Replicate Oracle's LISTAGG Function in SQL Server?

在SQL Server中模擬Oracle的LISTAGG函數

SQL Server本身並不包含LISTAGG函數,但可以透過多種方法實現類似的功能。

MySQL

<code class="language-sql">SELECT
  FieldA,
  GROUP_CONCAT(FieldB ORDER BY FieldB SEPARATOR ',') AS FieldBs
FROM
  TableName
GROUP BY
  FieldA
ORDER BY
  FieldA;</code>
登入後複製

Oracle & DB2

<code class="language-sql">SELECT
  FieldA,
  LISTAGG(FieldB, ',') WITHIN GROUP (ORDER BY FieldB) AS FieldBs
FROM
  TableName
GROUP BY
  FieldA
ORDER BY
  FieldA;</code>
登入後複製

PostgreSQL

<code class="language-sql">SELECT
  FieldA,
  STRING_AGG(FieldB, ',' ORDER BY FieldB) AS FieldBs
FROM
  TableName
GROUP BY
  FieldA
ORDER BY
  FieldA;</code>
登入後複製

SQL Server

SQL Server >= 2017 & Azure SQL

<code class="language-sql">SELECT
  FieldA,
  STRING_AGG(FieldB, ',') WITHIN GROUP (ORDER BY FieldB) AS FieldBs
FROM
  TableName
GROUP BY
  FieldA
ORDER BY
  FieldA;</code>
登入後複製

SQL Server (其他版本)

為了程式碼的可讀性和可維護性,這裡使用公用表表達式 (CTE):

<code class="language-sql">WITH CTE_TableName AS (
  SELECT
    FieldA,
    FieldB
  FROM
    TableName
)
SELECT
  t0.FieldA,
  STUFF(
    (
      SELECT
        ',' + t1.FieldB
      FROM
        CTE_TableName t1
      WHERE
        t1.FieldA = t0.FieldA
      ORDER BY
        t1.FieldB
      FOR XML PATH('')
    ),
    1,
    LEN(','),
    ''
  ) AS FieldBs
FROM
  CTE_TableName t0
GROUP BY
  t0.FieldA
ORDER BY
  FieldA;</code>
登入後複製

SQLite

需要排序時,需使用CTE或子查詢

<code class="language-sql">WITH CTE_TableName AS (
  SELECT
    FieldA,
    FieldB
  FROM
    TableName
  ORDER BY
    FieldA,
    FieldB
)
SELECT
  FieldA,
  GROUP_CONCAT(FieldB, ',') AS FieldBs
FROM
  CTE_TableName
GROUP BY
  FieldA
ORDER BY
  FieldA;</code>
登入後複製

無排序時

<code class="language-sql">SELECT
  FieldA,
  GROUP_CONCAT(FieldB, ',') AS FieldBs
FROM
  TableName
GROUP BY
  FieldA
ORDER BY
  FieldA;</code>
登入後複製

以上是如何在SQL Server複製Oracle的LISTAGG函數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板