日期:2014-05-18  浏览次数:20462 次

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 <> 3
union all
select B.* from
(
    select distinct name
    from table_name
    where type = 3
) A
cross apply 
(
    select top(1) * from table_name
    where name = A.name 
) B

------解决方案--------------------
SQL code
select id,name,secondname,type
from from t
where type <3
union all
select max(id),max(name),secondname,max(type)
from t
where type = 3
group by secondname
having count(secondname) = 2

------解决方案--------------------
SQL code
select distinct * from tb

------解决方案--------------------
SQL code
select id,name,secondname,type
from from t
where type <3
union all
select max(id),max(name),secondname,max(type)
from t
where type = 3
group by secondname
having count(secondname) = 2