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 必须自动生成我必须得到相同行组的计数

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 server 中做到这一点?

4

6 回答 6

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
于 2012-10-17T13:36:11.127 回答
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
于 2012-10-17T13:37:52.557 回答
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
于 2012-10-17T13:38:58.987 回答
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
于 2012-10-17T14:04:32.983 回答
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
于 2012-10-17T13:35:56.373 回答
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
于 2012-10-17T13:42:36.633 回答