我有一張員工表,評論分布在多行中。這些需要連接成一行。要確定可以連接哪些行,我們需要使用日期欄位 - 如果日期存在并且后續行沒有日期,則表示員工評論的開始。但是,如果有單行沒有日期且沒有先前的日期行,那么這將被視為新評論。還提供了輸入注釋的順序(身份列),因此 LEAD 功能是我嘗試的方式 下面的表格就是我們所擁有的: 表格截圖
| 員工ID | 日期 | 評論 | 命令 |
|---|---|---|---|
| 1001 | 2021-01-08 | 這只是第一部分 | 1 |
| 1001 | 無效的 | 這是第二個 | 2 |
| 1001 | 無效的 | 這是第三部分 | 3 |
| 1001 | 2021-01-15 | 這是相同的新評論 | 4 |
| 1002 | 2021-01-16 | 這個有后續評論 | 5 |
| 1002 | 2021-01-16 | 第二條評論 | 6 |
| 1003 | 無效的 | 這是單條評論 | 7 |
| 1003 | 2021-01-12 | 這也是單條評論 | 8 |
我們期望的結果是: Result Expected
| 員工ID | 日期 | 評論 | 命令 |
|---|---|---|---|
| 1001 | 2021-01-08 | 這只是第一部分 這是第二部分 這是第三部分 | 1 |
| 1001 | 無效的 | 這是相同的新評論 | 4 |
| 1002 | 2021-01-15 | 這個有后續評論 第二條評論 | 5 |
| 1003 | 2021-01-16 | 這是單條評論 | 7 |
| 1003 | 2021-01-16 | 這也是單條評論 | 8 |
我正在嘗試領先功能,但無法獲得如何根據條件加入 n 行。有什么幫助嗎?
SQL:
CREATE TABLE Comments(
[EmployeeID] [int] NOT NULL,
[Date] [date] null,
[Comment] [varchar](100) NULL,
[Order] [int] NULL
)
INSERT INTO Comments VALUES('1001','1/8/2021', 'This is only first part', 1)
INSERT INTO Comments VALUES('1001',NULL, 'this is the second', 2)
INSERT INTO Comments VALUES('1001',NULL, 'and this is third part', 3)
INSERT INTO Comments VALUES('1001','1/15/2021', 'This is a new comment for same', 4)
INSERT INTO Comments VALUES('1002','1/16/2021', 'This one has subsequent comment', 5)
INSERT INTO Comments VALUES('1002','1/16/2021', 'The second comment', 6)
INSERT INTO Comments VALUES('1003',NULL, 'This is single comment', 7)
INSERT INTO Comments VALUES('1003','1/12/2021', 'This is also single comment', 8)
uj5u.com熱心網友回復:
我在您的“預期結果”中留下了一堆關于細節的評論,鑒于您的要求,這些評論沒有意義。如果我按照您的要求進行,那么這是一個解決方案:
首先將表格標準化為具有日期,以便我們可以使用 group by
SELECT EmployeeID,
COALESCE([Date],
LAG([Date] OVER (ORDER BY [Order] ASC), -- Get the prior one if null
MIN([Date] OVER (PARTITION BY EmployeeID ORDER BY [Date] ASC)) AS [Date], -- Get the smallest one if the last two are null
Comment,
[Order]
FROM sometableyoudidnotname
現在我們有了這個表,我們可以使用 group by 和 string_agg
SELECT EmployeeID,
MIN(cDate) as [DATE],
STRING_AGG(Comment, ' ') WITHIN GROUP (ORDER BY [ORDER] ASC) AS Comment
FROM (
SELECT EmployeeID,
COALESCE([Date],
LAG([Date] OVER (ORDER BY [Order] ASC), -- Get the prior one if null
MIN([Date] OVER (PARTITION BY EmployeeID ORDER BY [Date] ASC)) AS [Date], -- Get the smallest one if the last two are null
Comment,
[Order]
FROM sometableyoudidnotname) X
GROUP BY EmployeeID
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/493668.html
標籤:sql服务器 tsql sql-server-2012
上一篇:從當前表生成新表
