逗号分隔的字符串
Comma Separated String
我想使用 T-SQL
return 来自我 table 的 select 签名的结果到逗号分隔的字符串
我想要这个
创建TABLE脚本
CREATE TABLE [dbo].[EVENT_TABLE](
[ID_PERSON] [bigint] IDENTITY(1,1) NOT NULL,
[ID_SIGNATURE] [bigint] NULL,
[Name] [varchar](250) NULL,
[Surname] [varchar](250) NULL,
[Age] [varchar](250) NULL,
[Department] [varchar](200) NULL,
CONSTRAINT [PK_PERSON_TABLE] PRIMARY KEY CLUSTERED
(
[ID_PERSON] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SELECT脚本
SELECT
DISTINCT
A.Department,
CASE
WHEN SUM(A.PEOPLE) < 5 THEN '1 TO 4'
WHEN SUM(A.PEOPLE) >= 5 AND A.PEOPLE < 10 THEN '5 TO 9'
WHEN SUM(A.PEOPLE) >= 10 THEN '10...N'
END
FROM
(
SELECT DISTINCT ID_SIGNATURE, Department, COUNT(NAME) AS PEOPLE
FROM EVENT_TABLE
GROUP BY ID_SIGNATURE, Department
) AS A
GROUP BY A.Department, A.PEOPLE
数据
结果
希望这就是您所需要的。您的代码中有两个不需要的东西,例如 Distinct, Aggregate
。试试这个。
;WITH cte
AS (SELECT A.Department,
CASE
WHEN A.PEOPLE < 5 THEN '1 TO 4'
WHEN A.PEOPLE >= 5 AND A.PEOPLE < 10 THEN '5 TO 9'
WHEN A.PEOPLE >= 10 THEN '10...N'
END [Range],
ID_SIGNATURE
FROM (SELECT ID_SIGNATURE,
Department,
Count(NAME) AS PEOPLE
FROM EVENT_TABLE
GROUP BY ID_SIGNATURE,
Department) AS A)
SELECT Department,
[Range],
(SELECT Stuff((SELECT ',' + CAST(ID_SIGNATURE AS varchar(20))
FROM cte a
WHERE a.Department = b.Department
AND a.[Range] = b.[Range]
FOR XML PATH ('')), 1, 1, '')) Signature
FROM cte B
GROUP BY Department,
[Range]
我想使用 T-SQL
return 来自我 table 的 select 签名的结果到逗号分隔的字符串我想要这个
创建TABLE脚本
CREATE TABLE [dbo].[EVENT_TABLE](
[ID_PERSON] [bigint] IDENTITY(1,1) NOT NULL,
[ID_SIGNATURE] [bigint] NULL,
[Name] [varchar](250) NULL,
[Surname] [varchar](250) NULL,
[Age] [varchar](250) NULL,
[Department] [varchar](200) NULL,
CONSTRAINT [PK_PERSON_TABLE] PRIMARY KEY CLUSTERED
(
[ID_PERSON] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SELECT脚本
SELECT
DISTINCT
A.Department,
CASE
WHEN SUM(A.PEOPLE) < 5 THEN '1 TO 4'
WHEN SUM(A.PEOPLE) >= 5 AND A.PEOPLE < 10 THEN '5 TO 9'
WHEN SUM(A.PEOPLE) >= 10 THEN '10...N'
END
FROM
(
SELECT DISTINCT ID_SIGNATURE, Department, COUNT(NAME) AS PEOPLE
FROM EVENT_TABLE
GROUP BY ID_SIGNATURE, Department
) AS A
GROUP BY A.Department, A.PEOPLE
数据
结果
希望这就是您所需要的。您的代码中有两个不需要的东西,例如 Distinct, Aggregate
。试试这个。
;WITH cte
AS (SELECT A.Department,
CASE
WHEN A.PEOPLE < 5 THEN '1 TO 4'
WHEN A.PEOPLE >= 5 AND A.PEOPLE < 10 THEN '5 TO 9'
WHEN A.PEOPLE >= 10 THEN '10...N'
END [Range],
ID_SIGNATURE
FROM (SELECT ID_SIGNATURE,
Department,
Count(NAME) AS PEOPLE
FROM EVENT_TABLE
GROUP BY ID_SIGNATURE,
Department) AS A)
SELECT Department,
[Range],
(SELECT Stuff((SELECT ',' + CAST(ID_SIGNATURE AS varchar(20))
FROM cte a
WHERE a.Department = b.Department
AND a.[Range] = b.[Range]
FOR XML PATH ('')), 1, 1, '')) Signature
FROM cte B
GROUP BY Department,
[Range]