2017-04-16 68 views
0

列假設我在SQL Server下表:SQL服務器選擇行與數

CREATE TABLE [dbo].[Table1](
    [ID] [int] IDENTITY(1,1) NOT NULL, 
    [Title] [nvarchar](max) NOT NULL, 
    [Value] [int] NOT NULL, 
CONSTRAINT [PK_Table1] PRIMARY KEY; 

,並在表中的這些值:

ID Title Value 
1  A  1 
2  B  2 
3  C  3 
4  D  4 
5  E  1 
6  F  1 
7  G  3 

,並假設每個標題重複最多3次。我想從只有那些具有重複值在該表的標題得到一個輸出,按以下格式:

Titl1 Title2 Title3 RepeatCount 
A  E  F  3 
C  G  NULL  2 

我寫了一個查詢來獲取重複的項目,但不知道如何輸出轉換爲這種格式在單個查詢中。這是查詢重複項目:

SELECT DISTINCT t1.Title, t1.Value, 
     (SELECT Count(Value) from Table1 where Table1.Value = t1.Value) as RepeatCount 
FROM Table1 t1 INNER JOIN 
    Table1 t2 
    ON t1.Title <> t2.Title AND t1.Value = t2.Value 
ORDER BY Value 

任何想法?

回答

1

我認爲這是一個有條件的聚集查詢:

select max(case when seqnum = 1 then title end) as title1, 
     max(case when seqnum = 2 then title end) as title2, 
     max(case when seqnum = 3 then title end) as title3, 
     count(*) as repeatcount 
from (select t.*, 
      row_number() over (partition by value order by id) as seqnum 
     from table1 t 
    ) t 
group by value 
having count(*) > 1; 
1

做相同的另一種方式,

declare @t table(ID int,Title varchar(20),Value int) 
insert into @t values 
(1,'A',1) 
,(2,'B',2) 
,(3,'C',3) 
,(4,'D',4) 
,(5,'E',1) 
,(6,'F',1) 
,(7,'G',3) 
;With CTE as 
(
SELECT * 
,ROW_NUMBER()over(partition by Value order by Value)rn 
from @t 
) 
,CTE1 AS 
(
SELECT * 
from cte c 
where exists(
select * from cte c1  
where c1.value=c.value and c1.rn>1 
) 
) 


select 
     (select title from cte1 c1 where c.value=c1.value and rn = 1)title1 
     ,(select title from cte1 c1 where c.value=c1.value and rn = 2) title2 
     ,(select title from cte1 c1 where c.value=c1.value and rn = 3) title3 
     ,(select max(rn) from cte1 c1 where c.value=c1.value) RepeatCount 
from cte1 c 

where rn=1