SQL:根据特定条件选择记录,合并重复记录 [英] SQL: select records based on certain criteria, merging records that are duplicates

查看:41
本文介绍了SQL:根据特定条件选择记录,合并重复记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个 SQL 语句来导出唯一的行列表.

鉴于这组数据,我希望结果删除重复的行,其中重复定义为 Column1 相同且第 2 列和第 3 列为空

事情:ID 列 1 列 2 列 31 和 42 比 73 米 94个5个6 a z 4

预期结果:

a, z, 4乙,乙,7乙,米,9一种,  ,a, z, 4

注意 a, z, 4 在结果中出现了两次,这是正确的.仅当 Column1 相同且 Column2 和 Column3 为空时才合并行.

我将如何构造查询来获得此结果?

解决方案

当它为非空时使用唯一的(因此不可分组的)id,当它为空时使用可分组的空应该可以工作.

>

选择Column1、Column2、Column3来自事物当 Column1 为空时按情况分组,否则为空,否则 ID 结束,当 Column2 为 null 时为 null,否则 ID 结束,当 Column3 为 null 然后为 null else ID end

I need an SQL statement that will derive a list of rows that are unique.

Given this set of data, I want the result to remove duplicate rows where duplicate is defined as Column1 being identical and column 2 and 3 are empty

Things:

ID    Column1    Column2        Column3
1        a          z              4
2        b          y              7
3        b          m              9
4        a                        
5        a 
6        a          z              4                       

Expected Result:

a, z, 4
b, y, 7
b, m, 9
a,  , 
a, z, 4

Note that a, z, 4 appears twice in the result and this is correct. Rows only get merged when Column1 is the same and Column2 and Column3 are empty.

How would I construct a query to get this result?

解决方案

Using the unique (and therefore non-group-able) id when it's non-null, and a group-able null when it's null should work.

select Column1, Column2, Column3
from Things
group by case when Column1 is null then null else ID end,
    case when Column2 is null then null else ID end,
    case when Column3 is null then null else ID end

这篇关于SQL:根据特定条件选择记录,合并重复记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆