![](/img/trans.png)
[英]How to concatenate multiple columns values into a single value per unique row
[英]How to concatenate values from multiple columns in a single row
我有這張表,我需要將幾列中的相同值連接到一行中。
RowId ServerName MyApplicationName UserName StartTime LastTime UsersCount
1 Prod MyProd User1 2021/03/09 2021/03/09 10
2 DEV1 MyApp1 User1 2021/03/12 2021/03/13 3
3 DEV1 MyApp1 User1 2021/03/14 2021/03/15 3
4 DEV1 MyApp1 User1 2021/03/16 2021/03/17 4
5 DEV1 MyApp1 User1 2021/03/18 2021/03/19 5
我需要以下結果:
RowId ServerName MyApplicationName UserName StartTime LastTime UsersCount
1 Prod MyProd User1 2021/03/09 2021/03/09 10
2 DEV1 MyApp1 User1 2021/03/12 2021/03/19 15
我嘗試了什么:
SELECT
RowId,
STUFF(
(SELECT ',' + ServerName
FROM tbl t1
WHERE t2.ServerName = t1.ServerName
FOR XML PATH(''))
, 1, 1, '')
) As ServerName,
STUFF(
(SELECT ',' + MyApplicationName
FROM tbl t1
WHERE t2.MyApplicationName = t1.MyApplicationName
FOR XML PATH(''))
, 1, 1, '')
) As MyApplicationName,
STUFF(
(SELECT ',' + UserName
FROM tbl t1
WHERE t2.UserName = t1.UserName
FOR XML PATH(''))
, 1, 1, '')
) As UserName,
MIN(StartTime) AS StartTime,
MAX(LastTime) AS LastTime,
SUM(UserCount) AS UserCount
GROUP BY ApplicationName
但它不起作用。 如何正確執行以及我做錯了什么?
這只是一個最小、最大、總和的練習,不是嗎?
--DROP TABLE t
CREATE TABLE t (
ServerName varchar(100),
myapplicationname varchar(100),
username varchar(100),
starttime varchar(100),
endtime varchar(100),
usercount int)
INSERT INTO t ( ServerName, myapplicationname, username, starttime, endtime, usercount)
VALUES
('Prod','myprod','user1','2021/03/09','2021/03/09', 10),
('dev1','MyApp1','user1','2021/03/12','2021/03/13', 3),
('dev1','MyApp1','user1','2021/03/14','2021/03/15', 3),
('dev1','MyApp1','user1','2021/03/16','2021/03/17', 5)
select *
from t
select ServerName, myapplicationname, username, min(starttime), max(endtime), sum(usercount)
from t
group by ServerName, myapplicationname, username
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.