How to JOIN two rows into one row SQL
Table 1:
ID | Name | Class | Date | Intime | Outtime | INAM | OUTPM |
---|---|---|---|---|---|---|---|
1 | Smith | 1st | 07-12-2022 | 8:30 AM | Null | P | Null |
1 | Smith | 1st | 07-12-2022 | Null | 4:30 P开发者_开发百科M | Null | P |
How to join these two rows into a single row?
Required output:
ID | Name | Class | Date | Intime | Outtime | INAM | OUTPM |
---|---|---|---|---|---|---|---|
1 | Smith | 1st | 07-12-2022 | 8:30 AM | 4:30 PM | P | P |
Can someone please help me to join into a single row? Thank you...
You may aggregate by the first 4 columns and take the max of the final 4 columns:
SELECT ID, Name, Class, Date,
MAX(Intime) AS Intime, MAX(Outtime) AS Outtime, MAX(INAM) AS INAM,
MAX(OUTPM) AS OUTPM
FROM yourTable
GROUP BY ID, Name, Class, Date;
SELECT
FK,
MAX(Field1) AS Field1,
MAX(Field2) AS Field2
FROM
table1
GROUP BY
FK;
I used MAX, but any aggregate which picks one value from among the GROUP BY rows should work.
Test data:
CREATE TABLE table1 (FK int, Field1 varchar(10), Field2 varchar(10));
INSERT INTO table1 VALUES (3, 'ABC', NULL);
INSERT INTO table1 VALUES (3, NULL, 'DEF');
INSERT INTO table1 VALUES (4, 'GHI', NULL);
INSERT INTO table1 VALUES (4, 'JKL', 'MNO');
INSERT INTO table1 VALUES (4, NULL, 'PQR');
Results:
FK Field1 Field2
-- ------ ------
3 ABC DEF
4 JKL PQR
精彩评论