SQL Server从多个列中删除Null

时间:2014-04-16 21:17:09

标签: sql sql-server

我有以下代码:

SELECT DISTINCT agentIds,
CASE WHEN bvagnt LIKE 'A%A' THEN bvname END AS [Level 1],
CASE WHEN bvagnt LIKE 'A%G' THEN bvname END AS [level 2],
CASE WHEN bvagnt LIKE 'A%M' THEN bvname END AS [level 3]
FROM agents

结果如下:

agentIds    Level 1         level 2                         level 3
A3090A      JASON COLBY     NULL                            NULL
A5097G      NULL            GARITY ASSOCIATES BROKERAGE     NULL
A8505M      NULL            NULL                            NAIM 

我想要的是,选择前1但我不想要任何Null,我希望结果没有agentIds列:

Level 1         level 2                         level 3
JASON COLBY     GARITY ASSOCIATES BROKERAGE     NAIM 

我做了where语句并且选择了每个列而不是NULL但是它没有工作并且没有产生期望的结果。

解决此问题的最佳方法是什么? 这是临时表:

CREATE TABLE #table1
(agentid varchar(5),
Level1 varchar(50),
Level2 varchar(50),
Level3 varchar(50))

INSERT INTO #table1 VALUES ('A123A', 'NULL', 'PartB', 'NULL')
INSERT INTO #table1 VALUES ('A123G', 'PartA', 'NULL', 'NULL')
INSERT INTO #table1 VALUES ('A123M', 'NULL', 'NULL', 'PartC')

SELECT * FROM #table1

DROP TABLE #table1

3 个答案:

答案 0 :(得分:0)

如果您只期望一个结果行,则以下查询将起作用:

SELECT a.bvname as [Level 1], b.bvname as [Level 2], c.bvname as [Level 3]
FROM
(SELECT bvname FROM agents where bvagnt LIKE 'A%A') a,
(SELECT bvname FROM agents where bvagnt LIKE 'A%G') b,
(SELECT bvname FROM agents where bvagnt LIKE 'A%M') c,

答案 1 :(得分:0)

不使用distinct,而是使用聚合:

SELECT MAX(CASE WHEN bvagnt LIKE 'A%A' THEN bvname END) AS [Level 1],
       MAX(CASE WHEN bvagnt LIKE 'A%G' THEN bvname END) AS [level 2],
       MAX(CASE WHEN bvagnt LIKE 'A%M' THEN bvname END) AS [level 3]
FROM agents;

答案 2 :(得分:0)

这是你在找什么?

SELECT MAX(LEVEL1) LEVEL1
, MAX(LEVEL2) LEVEL2
, MAX(LEVEL3) LEVEL3
FROM #table1

我假设每列只有1个合法值......