在 SQL Server 2016 中将每个列值 table 转换为 JSON

Convert table into JSON per column value in SQL Server 2016

我有以下 table:

CREATE TABLE #Temp
(
    customerId INT
  , storeCity VARCHAR(50)
  , transactionDate VARCHAR(100)
  , TransactionDescription VARCHAR(200)
  , Amount DECIMAL(18, 2)
)

INSERT INTO #Temp (customerId, storeCity, transactionDate, TransactionDescription, Amount)
VALUES (2, 'Neuwied', 'January 14th, 2018', 'Lorem ipsum dolor', 278),
       (1, 'Sunset Point', 'September 14th, 2018', 'Lorem ipsum dolor sit amet, consectetuer', 159),
       (1, 'Celle', 'March 18th, 2018', 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur', 47),
       (3, 'General Lagos', 'March 27th, 2018', 'Lorem', 433), 
       (2, 'Ekeren', 'January 16th, 2018', 'Lorem ipsum dolor sit amet, consectetuer adipiscing', 308),
       (3, 'Montreal', 'November 24th, 2018', 'Lorem', 406),
       (1, 'Hamilton', 'March 17th, 2018', 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur sed', 240)

我需要编写一个查询,在这个查询中我为这个 table 中的每个 customerId 得到一个 json 字符串。

到目前为止我有

SELECT   
    customerId,
    (SELECT 
         storeCity,
         transactionDate,
         TransactionDescription
     FOR JSON PATH, INCLUDE_NULL_VALUES)
FROM     
    #Temp
ORDER BY 
    1

但我想将所有这些结合起来,所以我最终只有 3 行。

对于 customerId 2,结果将是

[
  {
    "storeCity": "Neuwied",
    "transactionDate": "January 14th, 2018",
    "TransactionDescription": "Lorem ipsum dolor"
  },
  {
    "storeCity": "Ekeren",
    "transactionDate": "January 16th, 2018",
    "TransactionDescription": "Lorem ipsum dolor sit amet, consectetuer adipiscing"
  }
]

如果可能,我希望能够让 json 字符串中的行按 storeCity 排序,然后按 transactionDate 排序。

谁能帮我解决这个问题?

提前致谢。

试试这个:

select distinct customerId, (
                select StoreCity,
                       TransactionDate,
                       TransactionDescription
                from Temp
                where customerId = T.customerId
                for json path) [JSON]
from Temp T