T-SQL: как сгруппировать строки по определенному столбцу? - PullRequest
1 голос
/ 10 мая 2010
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 ]

3 голосов
/ 10 мая 2010

пример

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 голос
/ 10 мая 2010

Если вы имеете в виду, что вам нужно показывать только строки, для которых 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 )
1 голос
/ 10 мая 2010

Я думаю, что это может вам помочь.

SELECT DISTINCT IncreasmentAmount, Name, regionid, count(*)
FROM  Pricing.GroupOfRegions 
where regionid in (6,7) 
group by IncreasmentAmount, Name, regionid
having count(*) > 1
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...