开发者

T-SQL: how to group rows on a specific column?

SELECT DISTINCT 
        IncreasmentAmount,
        Name, 
        regionid
FROM         P开发者_StackOverflowricing.GroupOfRegions
WHERE   regionid in (6,7)

This statement produces this result:

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

I'd like to add more conditions where IncreasmentAmounts are equal. This would result in the rows that have the same IncreasmentAmount:

12.80 AB 6
12.80 AB 7

How can I modify the query to produce the results I want?


example

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)

here is one way of doing it

    --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)

or

  -- 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)


I think this can help you.

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


If you mean that you need to show only rows for which the 1st column equals some other row, then I am afraid you'll have to do a nested query like this:

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 )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜