SQL服务器,在表中查找不同的组

时间:2013-04-29 19:32:32

标签: sql group-by distinct relational-division

我有桌子

prdID    item     percentage
1        10         50
1        20         50
2        10         50
2        20         50
3        20         30
3        20         70
4        10         50
4        20         30
4        30         20
5        10         50
5        20         50

我想获取不同的组。基本上 结果集应该是

group   item     percentage
1        10        50
1        20        50
3        20        30
3        20        70
4        10        50
4        20        30
4        30        20

25从结果中排除,因为它们包含的item/percentage值与1完全相同

2 个答案:

答案 0 :(得分:0)

我认为这是您想要的查询:

SELECT MIN(prdId) AS group, item, percentage
FROM <tablename>
GROUP BY item, percentage

这将对您的示例数据产生以下结果:

group   item     percentage
1        10        50
1        20        50
3        20        30
3        20        70
4        30        20

(我认为你通过包含另外两个4来在你的示例输出中犯了一个小错误。他们(项目,百分比)值是组1和组3的重复。)

答案 1 :(得分:0)

select * 
from table_name t
inner join (
select min(prdID) as prdID
from
(
SELECT 
  table_name.prdID as prdID,
  STUFF((
    SELECT ',' + cast(item as varchar)+'~'+cast(percentage as varchar)
    FROM table_name t2
    WHERE t2.prdID = table_name.prdID
    FOR XML PATH (''))
,1,2,'') AS Names
FROM table_name
GROUP BY table_name.prdID
)t
group by Names)R
on t.prdID=R.prdID

<强> SQL FIDDLE