将多个行折叠为一行

时间:2014-08-15 00:14:25

标签: sql sql-server

在SQL Server中,我需要根据一列中的ID将多行折叠成一行。例如:

+-----------+-----------+
| objectIdA | objectIdB |
+-----------+-----------+
|         1 |         A |
|         1 |         B |
|         1 |         D |
|         5 |         F |
|         5 |         L |
|         7 |         C |
+-----------+-----------+

结果将是:

+-----------+-----------+
| objectIdA | objectIdB |
+-----------+-----------+
|         1 |         A |
|         5 |         L |
|         7 |         C |
+-----------+-----------+

一旦只有1,我不关心崩溃返回哪一行。

3 个答案:

答案 0 :(得分:1)

SELECT DISTINCT objectIdA
FROM your_table;

答案 1 :(得分:1)

因为您不关心返回哪一行

DECLARE @myTable TABLE (objectIdA int, objectIdB varchar(1));

INSERT INTO @myTable VALUES (1, 'A');
INSERT INTO @myTable VALUES (1, 'B');
INSERT INTO @myTable VALUES (1, 'D');
INSERT INTO @myTable VALUES (5, 'F');
INSERT INTO @myTable VALUES (5, 'L');
INSERT INTO @myTable VALUES (7, 'C');

SELECT objectIdA, MIN(objectIdB) AS objectIdB
 FROM @myTable
 GROUP BY objectIdA

答案 2 :(得分:0)

您可以使用PARTITION OVER。以下查询将执行您想要的操作。如果您愿意,可以调整ORDER BY来准确检索第一个或最后一个记录

SELECT 
        t.objectIdA,
        t.objectIdB
    FROM (
      SELECT 
        raw.objectIdA,
        raw.objectIdB,
        rowid = ROW_NUMBER() OVER (PARTITION BY raw.objectIdA ORDER BY raw.objectIdA)
      FROM yourTable raw
    ) t
    WHERE rowid <= 1

小提琴:http://sqlfiddle.com/#!3/60092/10