有难度的sql相同列值合并行

来源:百度知道 编辑:UC知道 时间:2024/07/05 21:51:04
原表:
商品名称 |长 |宽
商品1 100 110
商品1 100 110
商品1 110 100
商品2 100 110
商品2 110 110
商品2 110 120
商品2 110 120

要求结果为:商品名称,长,宽都相同则合并行(select distinct 商品名称,长,宽 from 原表 就可以,关键是后面的怎么处理)。 还有长为110宽为100 和 长为100宽为110的也要合并。

结果为:
商品名称 |长 |宽
商品1 100 110
商品2 100 110
商品2 110 110
商品2 110 120

有多种方法,这种方法最直观:
select distinct 商品名称,case when 宽<长 then 长 else 宽 end as 长,case when 宽<长 then 宽 else 长 end as 宽 from 原表

呵呵,这是我的强项,应该需要用到两个关键字,unino与except
unino将记录联合起来,except将记录进行排除,
具体的SQL语句如下:
select distinct 商品名称,长,宽 --将所有不同的记录查找出来
from 商品表
except --将所有有(长=100 and 宽 =110)或(长=110 and 宽 =100) 的记录排除出去
select distinct 商品名称,长,宽
union --将所有有(长=100 and 宽 =110)的记录增加进来
from 商品表
where (长=100 and 宽 =110) or (长=110 and 宽 =100)
union
select distinct 商品名称,长,宽
from 商品表
where 长=100 and 宽 =110
呵呵,希望能有帮助,^_^

楼上的就能实现你的要求:select 商品名称,长,宽 from table group by 商品名称,长,宽

select 商品名称,长,宽 from table group by 商品名称,长,宽

select * into #temp from 原表

update #temp
set 长=100,
宽=110
where 宽=100 and 长=110

select distinct 商品名称,长,宽 from #temp

你这个特殊况要先写代码,弄成一样的再SQL查询