我想删除一列(设备名称)中的重复项,但保留另一列(app_id)中的相关数据。每个设备可以有几个应用程序(1 -> x,通常在 1-5 之间)所以我想将这些应用程序标识符放入我想调用的新列中 [APP1]、[APP2]、[APP3] 等等. 最好的选择是动态 Pivot,但也欢迎任何静态解决方案。
提前感谢您的帮助。
PS我想出了下面的代码,但只是将用逗号分隔的APP id连接成一列。
USE tempdb;
SELECT DEVICE_NAME,
NoOfApps,
STUFF(( SELECT ', ' + APP_ID
FROM dbo.Aperture_full_test apps
WHERE apps.DEVICE_NAME = Aperture_full_test.DEVICE_NAME
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)'), 1, 2, '') AS Appid
FROM ( SELECT DEVICE_NAME, COUNT(DEVICE_NAME) AS NoOfApps
FROM dbo.Aperture_full_test
GROUP BY DEVICE_NAME
) Aperture_full_test
ORDER BY NoOfApps DESC
数据样本:
USE tempdb;
GO
IF OBJECT_ID('dbo.Aperture_full_test') IS NOT NULL
DROP TABLE dbo.Aperture_full_test;
GO
CREATE TABLE dbo.Aperture_full_test
(
DEVICE_NAME varchar(30) NOT NULL,
APP_ID varchar(10) NOT NULL
);
INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
VALUES('LDNSQLF700', 157848);
INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
VALUES('LDNSQLF700', 155439);
INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
VALUES('LDNSQLF700', 635533);
INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
VALUES('NYSQL502', 189164);
INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
VALUES('NYSQL502', 188641);
INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
VALUES('AUSSQL140', 537990);
INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
VALUES('AUSSQL140', 1349605);
INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
VALUES('JAP543X2', 5646789);
INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
VALUES('EU456CLX', 6545789);
INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
VALUES('EUCTX654', 5637965);
INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
VALUES('EUCTX654', 6464367) ;
INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
VALUES('EUCTX654', 1323123) ;
INSERT INTO dbo.Aperture_full_test(DEVICE_NAME, APP_ID)
VALUES('EUCTX654', 1004326) ;
GO