没有join怎么把一列拆分成多列呢?
How can I do without join to split one columns into multiple columns?
医疗保健:
A
B
ID
582
X
1
582
Y
2
755
123
1
755
456
2
811
abc
1
811
def
2
期望结果:
ID
A
B
C
D
E
F
1
582
X
755
123
811
abc
2
582
Y
755
456
811
def
或
ID
582
755
811
1
X
123
abc
2
Y
456
def
我可以这样做:
SELECT ID, A, B
FROM HealthCare as a
LEFT JOIN (select A as C, B as D from HealthCare where A = 755) as b
ON a.ID = b.ID
LEFT JOIN (select A as E, B as F from HealthCare where A = 811) as c
ON a.ID = c.ID
WHERE A = 582
有什么方法可以在没有连接或更少连接的情况下执行此操作?
如果你不想用JOIN
我觉得可以尝试用条件聚合函数来做,尝试在CASE WHEN
表达式中加入条件
SELECT ID,
MAX(CASE WHEN A = 582 THEN A END) 'A',
MAX(CASE WHEN A = 582 THEN B END) 'B',
MAX(CASE WHEN A = 755 THEN A END) 'C',
MAX(CASE WHEN A = 755 THEN B END) 'D',
MAX(CASE WHEN A = 582 THEN B END) 'E',
MAX(CASE WHEN A = 811 THEN B END) 'F'
FROM HealthCare
GROUP BY ID
医疗保健:
A | B | ID |
---|---|---|
582 | X | 1 |
582 | Y | 2 |
755 | 123 | 1 |
755 | 456 | 2 |
811 | abc | 1 |
811 | def | 2 |
期望结果:
ID | A | B | C | D | E | F |
---|---|---|---|---|---|---|
1 | 582 | X | 755 | 123 | 811 | abc |
2 | 582 | Y | 755 | 456 | 811 | def |
或
ID | 582 | 755 | 811 |
---|---|---|---|
1 | X | 123 | abc |
2 | Y | 456 | def |
我可以这样做:
SELECT ID, A, B
FROM HealthCare as a
LEFT JOIN (select A as C, B as D from HealthCare where A = 755) as b
ON a.ID = b.ID
LEFT JOIN (select A as E, B as F from HealthCare where A = 811) as c
ON a.ID = c.ID
WHERE A = 582
有什么方法可以在没有连接或更少连接的情况下执行此操作?
如果你不想用JOIN
我觉得可以尝试用条件聚合函数来做,尝试在CASE WHEN
表达式中加入条件
SELECT ID,
MAX(CASE WHEN A = 582 THEN A END) 'A',
MAX(CASE WHEN A = 582 THEN B END) 'B',
MAX(CASE WHEN A = 755 THEN A END) 'C',
MAX(CASE WHEN A = 755 THEN B END) 'D',
MAX(CASE WHEN A = 582 THEN B END) 'E',
MAX(CASE WHEN A = 811 THEN B END) 'F'
FROM HealthCare
GROUP BY ID