将多行分组到单行sql中

时间:2014-12-12 02:36:41

标签: sql-server

我的日志表包含以下数据

TransID  Name     Operation               Time
1       xyz       before update          2014-12-10 10:35:35.927
1       xyz1      after update           2014-12-10 10:35:35.943
2       abc       before update          2014-12-10 12:49:56.370
2       abc1      after update           2014-12-10 12:49:56.373

我需要输出类似下面的内容

Type     before update     after update          Time
Name    xyz               xyz1                   2014-12-10 10:35:35.927
Name    abc               abc1                   2014-12-10 12:49:56.370

需要有关sql查询的帮助。

由于

1 个答案:

答案 0 :(得分:1)

试试这个:

构建示例数据

CREATE TABLE LogTable(
    TransID     INT,
    Name        VARCHAR(20),
    Operation   VARCHAR(20),
    [Time]      DATETIME
)
INSERT INTO LogTable VALUES
(1, 'xyz', 'before update', '2014-12-10 10:35:35.927'),
(1, 'xyz1', 'after update', '2014-12-10 10:35:35.943'),
(2, 'abc', 'before update', '2014-12-10 12:49:56.370'),
(2, 'abc1', 'after update', '2014-12-10 12:49:56.373')

SELECT
    t.*,
    l.Time
FROM (
    SELECT
        Type = 'Name',
        [Before Update] = MAX(CASE WHEN Operation = 'before update' THEN Name END),
        [After Update] = MAX(CASE WHEN Operation = 'after update' THEN Name END)
    FROM LogTable
    GROUP BY TRANSID
)t
JOIN LogTable l on t.[Before Update] = l.Name