有人可以在这个简单的查询中找到语法错​​误吗?

时间:2018-04-03 12:27:18

标签: sql sql-server aggregate-functions string-function

请帮我解决此错误。

SELECT StateProvince,STRING_AGG(AddressID, ',') WITHIN GROUP (ORDER BY AddressID)
FROM [SalesLT].[Address] GROUP BY StateProvince;

我无法在此找到错误,但它说

  

'('。

附近的语法不正确

3 个答案:

答案 0 :(得分:1)

FOR SQL SERVER 2017

SELECT StateProvince,
       STRING_AGG(AddressID, ',') WITHIN GROUP (ORDER BY AddressID) AS AddressID
FROM [SalesLT].[Address] GROUP BY StateProvince;

<强>样本

  

http://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=69e5f9e9c5f3cab62e4b2eb9fb678299

FOR SQL SERVER 2017年以下

SELECT
      StateProvince, 
      AddressID = STUFF((
          SELECT ',' + CAST(md.AddressID AS NVARCHAR)
          FROM [SalesLT].[Address] md
          WHERE m.StateProvince = md.StateProvince
          ORDER BY AddressID
          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM [SalesLT].[Address] m
Group by StateProvince

样本

  

http://dbfiddle.uk/?rdbms=sqlserver_2012&fiddle=a1722450c70c946e9b53ae23785f4919

答案 1 :(得分:0)

我无法看到与您收到的消息相关的错误。对于大数据,它会抱怨大约8000字节的限制。这在MS SQL 2017,AdventureWorks示例数据库(不是具有较少数据的精简数据库)下工作正常:

SELECT StateProvinceID,
       STRING_AGG(cast(AddressID as varchar(MAX)), ',') WITHIN GROUP (ORDER BY AddressID) as AdressIDS
FROM [Person].[Address] 
GROUP BY StateProvinceID;

答案 2 :(得分:0)

将数据库从SQL 2008R2升级到2017后出现相同的问题。通过将兼容性级别设置为110(或更高?)来解决此问题