当前位置: 代码迷 >> Sql Server >> sql中怎么按类别取数据
  详细解决方案

sql中怎么按类别取数据

热度:76   发布时间:2016-04-27 12:01:28.0
sql中如何按类别取数据?
原始的数据
id name secondname type
1 商品一 1
1 商品一 1
2 商品二 2
3 商品三 套餐一 3
3 商品三 套餐一 3 
3 商品四 套餐二 3
3 商品四 套餐二 3

现在想要的数据
id name secondname type
1 商品一 1
2 商品二 2
3 商品三 套餐一 3 
3 商品四 套餐二 3

我是想,只要类别为3的,都要取他相同secondname的一条记录。别的类别是不管重复不重复都要全部取完。
有没有Sql语句能一下子就取完的,谢谢大家。

------解决方案--------------------
SQL code
select * from table_name where type <> 3union allselect B.* from(    select distinct name    from table_name    where type = 3) Across apply (    select top(1) * from table_name    where name = A.name ) B
------解决方案--------------------
SQL code
select id,name,secondname,typefrom from twhere type <3union allselect max(id),max(name),secondname,max(type)from twhere type = 3group by secondnamehaving count(secondname) = 2
------解决方案--------------------
SQL code
select distinct * from tb
------解决方案--------------------
SQL code
select id,name,secondname,typefrom from twhere type <3union allselect max(id),max(name),secondname,max(type)from twhere type = 3group by secondnamehaving count(secondname) = 2
  相关解决方案