我有一张表:
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中执行此操作?
答案 0 :(得分: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 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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
答案 4 :(得分: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
答案 5 :(得分: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