根据一列选择一个重复行

时间:2016-03-01 19:57:21

标签: sql sql-server

我一直在尝试根据一列过滤掉重复的行。

SELECT DISTINCT
    a.id,
    b.name,
    b.number
FROM
    b
LEFT JOIN a
    ON a.name = b.name
ORDER BY
    b.name
ASC;

结果是:

id,name,number
1  Bob  NULL
1  Bob  100
2  Bob  NULL
2  Bob  200
3  Bob  NULL
3  Bob  300
4  Bob  400

我试图达到这样的结果:

id,name,number
1  Bob  100
2  Bob  200
3  Bob  300
4  Bob  400

2 个答案:

答案 0 :(得分:0)

您可以使用ROW_NUMBER来有选择地过滤NULL字段中的b.number值:

SELECT id, name, number
FROM (
  SELECT a.id, b.name, b.number,
         ROW_NUMBER() OVER (ORDER BY COALESCE(b.number, -1) DESC) AS rn 
  FROM b
  LEFT JOIN a ON a.name = b.name) AS t
  WHERE t.rn = 1
ORDER BY name ASC

上述查询仅处理每个id一个或最多两行的案例,其中一个或两者都是NULL

答案 1 :(得分:0)

如果要合并NULL值,我建议汇总:

SELECT a.id, b.name, SUM(b.number) as number
FROM b LEFT JOIN
     a
     ON a.name = b.name
GROUP BY a.id, b.name;

或者,只需使用WHERE子句:

SELECT a.id, b.name, b.number
FROM b LEFT JOIN
     a
     ON a.name = b.name
WHERE b.name IS NOT NULL;