我有下表:
CREATE TABLE Colors (
name INT,
color CHAR(1)
);
INSERT INTO Colors (name, color) VALUES
(1, 'r'),
(1, 'r'),
(1, 'b'),
(2, 'b'),
(2, 'b'),
(2, 'r'),
(3, 'b'),
(3, 'b'),
(4, 'r');
name color
1 r
1 r
1 b
2 b
2 b
2 r
3 b
3 b
4 r
我想在此表中添加一列,说明每个名称属于哪种颜色:
name color new
1 r r and b
1 r r and b
1 b r and b
2 b r and b
2 b r and b
2 r r and b
3 b only b
3 b only b
4 r only r
通常,我会使用 unique 语句来执行此操作:
SELECT
C.name,
C.color,
CASE
WHEN COUNT(DISTINCT C1.color) > 1 THEN 'r and b'
WHEN MAX(C1.color) = 'r' THEN 'only r'
ELSE 'only b'
END as new
FROM
myt C
JOIN
myt C1 ON C.name = C1.name
GROUP BY
C.name,
C.color;
但我正在尝试重写这段代码,以便它明确地查看名称是否有红色或蓝色......而不仅仅是使用不同的颜色。
有人可以告诉我如何重写这个 SQL 代码吗?
谢谢!
尝试使用 CONCAT:
WITH ColorSummary AS (
SELECT
name,
CASE
WHEN COUNT(DISTINCT color) = 1 THEN CONCAT('only ', MIN(color))
ELSE 'r and b'
END AS color_summary
FROM Colors
GROUP BY name
)
SELECT
c.name,
c.color,
cs.color_summary AS new
FROM
Colors c
JOIN
ColorSummary cs
ON
c.name = cs.name;
输出:
名字 | 颜色 | 新 |
---|---|---|
1 | r | r 和 b |
1 | r | r 和 b |
1 | b | r 和 b |
2 | b | r 和 b |
2 | b | r 和 b |
2 | r | r 和 b |
3 | b | 只有b |
3 | b | 只有b |
4 | r | 只有r |