SQL - 将不同的行合并为具有不同 ID 的单行
SQL - Combine different rows into a single row with different ID
来自不同id的table需要合并成一行
+-----+-----+-----+-----+
| Id | Col1| Col2| Col3|
+-----+-----+-----+-----+
| 1 | | 1 | |
| 2 | | 2 | |
| 3 | 3 | | |
| 4 | 4 | | |
| 5 | | | 5 |
| 6 | | | 6 |
+-----+-----+-----+-----+
我想在同一个 table 中实现什么。
+-----+-----+-----+-----+
| Id | Col1| Col2| Col3|
+-----+-----+-----+-----+
| 1 | 3 | 1 | 5 |
| 2 | 4 | 2 | 6 |
+-----+-----+-----+-----+
我曾尝试使用不同的 id 聚合行
Select ID
,ID1 = max(Col1)
,ID2 = max(Col2)
,ID3 = max(Col3)
From Tbl
Group By ID
我不知道你想从这个结果中得到什么,但你可以尝试这样的查询:
Select ID
,(select max(Col1) from tbl) as ID1
,(select max(Col2) from tbl) as ID2
,(select max(Col3) from tbl) as ID3
From Tbl
Group By ID
您的数据
create table test(
Id INTEGER NOT NULL
,Col1 INTEGER
,Col2 INTEGER
,Col3 INTEGER
);
INSERT INTO test
(Id,Col1,Col2,Col3)
VALUES
(1,NULL,1,NULL),
(2,NULL,2,NULL),
(3,3,NULL,NULL),
(4,4,NULL,NULL),
(5,NULL,NULL,5),
(6,NULL,NULL,6);
UNION
Max
函数与 Min
函数的结果
SELECT 1 AS ID,
Min(col1) Col1,
Min(col2) Col2,
Min(col3) Col3
FROM test
UNION
SELECT 2 AS ID,
Max(col1) Col1,
Max(col2) Col2,
Max(col3) Col3
FROM test
另外你可以使用multiple join
和Subbquery
和Where
条件来
SELECT a.id1 AS id,
b.col1,
a.col2,
c.col3
FROM (SELECT Row_number()
OVER (
ORDER BY id ) id1,
*
FROM Test
WHERE col2 IS NOT NULL) a
JOIN (SELECT Row_number()
OVER (
ORDER BY id ) id1,
*
FROM Test
WHERE col1 IS NOT NULL) b
ON a.id1 = b.id1
JOIN(SELECT Row_number()
OVER (
ORDER BY id ) id1,
*
FROM Test
WHERE col3 IS NOT NULL) c
ON a.id1 = c.id1
来自不同id的table需要合并成一行
+-----+-----+-----+-----+
| Id | Col1| Col2| Col3|
+-----+-----+-----+-----+
| 1 | | 1 | |
| 2 | | 2 | |
| 3 | 3 | | |
| 4 | 4 | | |
| 5 | | | 5 |
| 6 | | | 6 |
+-----+-----+-----+-----+
我想在同一个 table 中实现什么。
+-----+-----+-----+-----+
| Id | Col1| Col2| Col3|
+-----+-----+-----+-----+
| 1 | 3 | 1 | 5 |
| 2 | 4 | 2 | 6 |
+-----+-----+-----+-----+
我曾尝试使用不同的 id 聚合行
Select ID
,ID1 = max(Col1)
,ID2 = max(Col2)
,ID3 = max(Col3)
From Tbl
Group By ID
我不知道你想从这个结果中得到什么,但你可以尝试这样的查询:
Select ID
,(select max(Col1) from tbl) as ID1
,(select max(Col2) from tbl) as ID2
,(select max(Col3) from tbl) as ID3
From Tbl
Group By ID
您的数据
create table test(
Id INTEGER NOT NULL
,Col1 INTEGER
,Col2 INTEGER
,Col3 INTEGER
);
INSERT INTO test
(Id,Col1,Col2,Col3)
VALUES
(1,NULL,1,NULL),
(2,NULL,2,NULL),
(3,3,NULL,NULL),
(4,4,NULL,NULL),
(5,NULL,NULL,5),
(6,NULL,NULL,6);
UNION
Max
函数与 Min
函数的结果
SELECT 1 AS ID,
Min(col1) Col1,
Min(col2) Col2,
Min(col3) Col3
FROM test
UNION
SELECT 2 AS ID,
Max(col1) Col1,
Max(col2) Col2,
Max(col3) Col3
FROM test
另外你可以使用multiple join
和Subbquery
和Where
条件来
SELECT a.id1 AS id,
b.col1,
a.col2,
c.col3
FROM (SELECT Row_number()
OVER (
ORDER BY id ) id1,
*
FROM Test
WHERE col2 IS NOT NULL) a
JOIN (SELECT Row_number()
OVER (
ORDER BY id ) id1,
*
FROM Test
WHERE col1 IS NOT NULL) b
ON a.id1 = b.id1
JOIN(SELECT Row_number()
OVER (
ORDER BY id ) id1,
*
FROM Test
WHERE col3 IS NOT NULL) c
ON a.id1 = c.id1