行到单个单元格

时间:2016-09-22 09:28:02

标签: sql sql-server sql-server-2012

我希望以绿色

标记所需的输出

enter image description here

将每个id的数据点放入单个单元格

基本上采用A发生的所有事件并以相同的顺序附加

4 个答案:

答案 0 :(得分:2)

使用资料功能

DECLARE @tblTest AS Table(
    ID INT,
    EVENT VARCHAR(5)
)

INSERT INTO @tblTest VALUES
(1,'A'),
(1,'A'),
(1,'C'),
(2,'A'),
(2,'B'),
(2,'C')

SELECT DISTINCT
    T1.ID,
    STUFF
    (
         (SELECT '' + convert(varchar(10), T2.EVENT, 120)
          FROM @tblTest T2
          where T1.ID = T2.ID
          FOR XML PATH (''))
    , 1, 0, '')  AS EVENT
FROM @tblTest T1

答案 1 :(得分:2)

您可以使用UDF执行以下操作:

CREATE TABLE t(
id INT,
col CHAR(1)
);

INSERT INTO t VALUES (1,'a');
INSERT INTO t VALUES (1,'b');
INSERT INTO t VALUES (1,'c');
INSERT INTO t VALUES (1,'d');
INSERT INTO t VALUES (2,'e');
INSERT INTO t VALUES (2,'f');
INSERT INTO t VALUES (3,'g');
INSERT INTO t VALUES (4,'h');

UDF(用户定义的函数) -

USE [t]
GO
CREATE FUNCTION dbo.ConcatenateCols(@Id INT)

RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @RtnStr VARCHAR(MAX)

SELECT @RtnStr = COALESCE(@RtnStr + '','') + col
FROM dbo.t
WHERE id = @Id AND col > ''
RETURN @RtnStr

END
GO

最后查询和结果:

SELECT id, dbo.ConcatenateCols(id) AS Cols -- UDF - ConcatenateCols(id)
FROM t GROUP BY Id

concatenate_col

答案 2 :(得分:1)

您可以使用FOR XML:

SELECT DISTINCT 
            ID,
            (SELECT [EVENT] +''
            FROM YourTable
            WHERE ID = y.ID
            FOR XML PATH('')
            ) as [EVENT]
FROM YourTable y

输出:

ID  EVENT
1   AABCD
2   AABBCC

答案 3 :(得分:1)

CREATE TABLE #temp(Id INt,Event Nvarchar(25))
INSERT INTO #temp
SELECT 1,
       'A'
UNION ALL
SELECT 1,
       'A'
UNION ALL
SELECT 1,
       'B'
UNION ALL
SELECT 1,
       'C'
UNION ALL
SELECT 1,
       'D'
UNION ALL
SELECT 2,
       'A'
UNION ALL
SELECT 2,
       'A'
UNION ALL
SELECT 2,
       'B'
UNION ALL
SELECT 2,
       'B'
UNION ALL
SELECT 2,
       'C'
UNION ALL
SELECT 2,
       'C'
SELECT DISTINCT ID,

  (SELECT [EVENT] +''
   FROM #temp
   WHERE ID = y.ID
     FOR XML PATH('') ) AS [EVENT]
FROM #temp y