T-SQL:如何对特定列上的行进行分组?

时间:2010-05-10 15:29:21

标签: sql-server-2005 tsql

SELECT DISTINCT 
        IncreasmentAmount,
        Name, 
        regionid
FROM         Pricing.GroupOfRegions
WHERE   regionid in (6,7)

此语句产生以下结果:

12.80 AB 6
13.00 ABC 6
15.00 AC 6
12.80 AB 7
13.00 ABC 7

我想添加IncreasmentAmount s相等的更多条件。这将导致具有相同IncreasmentAmount的行:

12.80 AB 6
12.80 AB 7

如何修改查询以生成我想要的结果?

3 个答案:

答案 0 :(得分:3)

例如

create table #bla(IncreasmentAmount decimal(16,2),Name varchar(40),regionid int)
insert #bla values(12.80, 'AB', 6)
insert #bla values(13.00, 'ABC', 6)
insert #bla values(15.00, 'AC', 6)
insert #bla values(12.80, 'AB', 7)
insert #bla values(13.00, 'ABC', 7)

这是一种方法

    --group also by name
select b.* from(
SELECT  IncreasmentAmount, Name
FROM         #bla
where regionid in (6,7)
group by IncreasmentAmount, Name
having count(*) > 1) as a
join #bla b on a.IncreasmentAmount = b.IncreasmentAmount
and a.Name = b.Name
where b.regionid in (6,7)

  -- don not group by name
select b.* from(
SELECT  IncreasmentAmount
FROM         #bla
where regionid in (6,7)
group by IncreasmentAmount
having count(*) > 1) as a
join #bla b on a.IncreasmentAmount = b.IncreasmentAmount
where b.regionid in (6,7)

答案 1 :(得分:1)

我认为这可以帮助你。

SELECT DISTINCT IncreasmentAmount, Name, regionid, count(*)
FROM  Pricing.GroupOfRegions 
where regionid in (6,7) 
group by IncreasmentAmount, Name, regionid
having count(*) > 1

答案 2 :(得分:1)

如果你的意思是你只需要显示第1列等于其他行的行,那么我恐怕你必须这样做一个嵌套查询:

SELECT DISTINCT IncreasmentAmount, Name, regionid
FROM         Pricing.GroupOfRegions

where regionid in (6,7)
and IncreasmentAmount IN (select IncreasmentAmount 
                          from Pricing.GroupOfRegions 
                          group by IncreasmentAmount 
                          having COUNT(*) > 1 )