我在桌子上有这样的东西
COUNTRY SCOPE1 SCOPE2 SCOPE3 SCOPE4 SCOPE5
UK Y NULL NULL NULL NULL
UK NULL Y NULL NULL NULL
UK NULL NULL Y NULL NULL
我需要将输出作为单行
COUNTRY SCOPE1 SCOPE2 SCOPE3 SCOPE4 SCOPE5
UK Y Y Y NULL NULL
有人可以在MS SQL Server 2014中对此提供帮助吗?
答案 0 :(得分:5)
您可以尝试使用MAX
函数。
CREATE TABLE T(
COUNTRY VARCHAR(50),
SCOPE1 VARCHAR(3),
SCOPE2 VARCHAR(3),
SCOPE3 VARCHAR(3),
SCOPE4 VARCHAR(3),
SCOPE5 VARCHAR(3)
);
INSERT INTO T VALUES ('UK','Y',NULL,NULL,NULL,NULL);
INSERT INTO T VALUES ('UK',NULL,'Y',NULL,NULL,NULL);
INSERT INTO T VALUES ('UK',NULL,NULL,'Y',NULL,NULL);
查询1 :
SELECT COUNTRY ,
MAX(SCOPE1) AS SCOPE1,
MAX(SCOPE2) AS SCOPE2,
MAX(SCOPE3) AS SCOPE3,
MAX(SCOPE4) AS SCOPE4,
MAX(SCOPE5) AS SCOPE5
FROM T
GROUP BY COUNTRY
Results :
| COUNTRY | SCOPE1 | SCOPE2 | SCOPE3 | SCOPE4 | SCOPE5 |
|---------|--------|--------|--------|--------|--------|
| UK | Y | Y | Y | (null) | (null) |
答案 1 :(得分:2)
您可以使用聚合函数max
或min
都适用于您的数据集
SELECT COUNTRY ,
MAX(SCOPE1) as SCOPE1,
MAX(SCOPE2) as SCOPE2,
MAX(SCOPE3) as SCOPE3,
MAX(SCOPE4) as SCOPE4,
MAX(SCOPE5) as SCOPE5
FROM yourtable
GROUP BY COUNTRY
http://sqlfiddle.com/#!18/3960c/1
COUNTRY SCOPE1 SCOPE2 SCOPE3 SCOPE4 SCOPE5
UK Y Y Y (null) (null)
或
SELECT COUNTRY ,
min(SCOPE1) as SCOPE1,
min(SCOPE2) as SCOPE2,
min(SCOPE3) as SCOPE3,
min(SCOPE4) as SCOPE4,
min(SCOPE5) as SCOPE5
FROM yourtable
GROUP BY COUNTRY
http://sqlfiddle.com/#!18/3960c/2
COUNTRY SCOPE1 SCOPE2 SCOPE3 SCOPE4 SCOPE5
UK Y Y Y (null) (null)