2012-10-17 49 views
2

我有這樣一個表:怎麼走集團同類行

Table1 
--------------------- 
Id |Kind1|Kind2|Kind3| 
--------------------- 
1 | 2 | 2 | 3 | * 
--------------------- 
2 | 2 | 2 | 2 | + 
--------------------- 
3 | 2 | 2 | 1 | 
--------------------- 
4 | 2 | 2 | 3 | * 
--------------------- 
5 | 2 | 1 | 1 | 
--------------------- 
6 | 1 | 1 | 1 | 
--------------------- 
7 | 2 | 2 | 2 | + 
---------------------- 

而且我想要得到那個結果如下圖所示的Id必須產生automaticaly 我一定要得到相同的行組

的數
Result 
------------------------------ 
Id | Count |New1 |New2 |New3 | 
------------------------------ 
1 | 2 | 2 | 2 | 2 | 
------------------------------ 
2 | 2 | 2 | 2 | 3 | 
------------------------------ 
3 | 1 | 2 | 2 | 1 | 
------------------------------ 
4 | 1 | 2 | 1 | 1 | 
------------------------------ 
5 | 1 | 1 | 1 | 1 | 
------------------------------ 

我該怎麼做在sql服務器?

回答

1
select ROW_NUMBER() over (order by (select 0)) as ID,count(*) as count,kind1 as new1,kind2 as new2,kind3 as new3 
from yourtable 
group by kind1,kind2,kind3 
1
;WITH CTE 
AS 
(
    SELECT Kind1, Kind2, Kind3, COUNT(*) 'Count' 
    FROM TableName 
    GROUP BY Kind1, Kind2, Kind3 
) 
SELECT 
    ROW_NUMBER()(OVER ORDER BY SELECT 0) Id, 
    [Count], 
    Kind1 AS New1, Kind2 AS New2, Kind3 AS New3 
FROM CTE 
1

你可以組上(kind1, kind2, kind3)

select row_number() over (order by min(Id)) as Id 
,  count(*) as [Count] 
,  kind1 
,  kind2 
,  kind3 
from YourTable 
group by 
     kind1 
,  kind2 
,  kind3 
1
BEGIN 
DECLARE @t TABLE (
    id INT PRIMARY KEY 
    ,kind1 INT 
    ,kind2 INT 
    ,kind3 INT 
) 
INSERT INTO @t 
VALUES (1, 1,1,1) 
    ,(2, 1,1,2) 
    , (3, 2,2,2) 
    , (4, 1,1,1) 

SELECT 
    ROW_NUMBER() OVER (ORDER BY kind1, kind2, kind3) [id] 
    ,COUNT(*) [count] 
    ,kind1 
    ,kind2 
    ,kind3 
FROM @t 
GROUP BY kind1, kind2, kind3 

END 
1
declare @Temp table (id int, kind1 int, kind2 int, kind3 int) 

insert into @Temp 
select 1, 2, 2, 3 union all 
select 2, 2, 2, 2 union all 
select 3, 2, 2, 1 union all 
select 4, 2, 2, 3 union all 
select 5, 2, 1, 1 union all 
select 6, 1, 1, 1 union all 
select 7, 2, 2, 2 

select 
    row_number() over (order by min(T.id)) as id, 
    count(*), 
    T.kind1, T.kind2, T.kind3 
from @Temp as T 
group by T.kind1, T.kind2, T.kind3 
1

像這樣的東西應該得到你想要的東西

SELECT Row_Number() Over (Order By cnt desc, kind1 desc, kind2 desc, kind3 desc) as id 
    , a.* 
FROM (
SELECT COUNT(*) cnt, kind1, kind2, kind3 
    FROM table1 
GROUP BY kind1, kind2, kind3 
) a