首页 > 数据库 > 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
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板