我有一个包含很多行的临时表(#TümDATA)。我是带有子句INSERT
的另一个临时表(#GrupTOT)中的行。GROUP BY
但是我被困在这里,我需要在它们被分组后给它们一个序号。
这是我的 SQL:
INSERT INTO #GrupTOT(AY, BLK, DRE, TOT)
SELECT J.AY, J.BLK, J.DRE, SUM(J.BORÇ)
FROM #TümDATA J
GROUP BY J.AY, J.BLK, J.DRE
我有一个包含很多行的临时表(#TümDATA)。我是带有子句INSERT
的另一个临时表(#GrupTOT)中的行。GROUP BY
但是我被困在这里,我需要在它们被分组后给它们一个序号。
这是我的 SQL:
INSERT INTO #GrupTOT(AY, BLK, DRE, TOT)
SELECT J.AY, J.BLK, J.DRE, SUM(J.BORÇ)
FROM #TümDATA J
GROUP BY J.AY, J.BLK, J.DRE
您可以使用ROW_NUMBER
来获取基于ORDER BY
. IDENTITY
或者,如果这是您想要的,您可以添加一列以在插入时自动增加一个数字。
ROW_NUMBER
方法:
WITH CTE AS
(
SELECT Col1, Col2, Col3, Count(*) as [COUNT]
FROM dbo.Table1
GROUP BY Col1, Col2, Col3
)
INSERT INTO dbo.Table2
SELECT RowNum = ROW_NUMBER() OVER ( ORDER BY Col1, Col2, Col3, [COUNT] DESC ),
Col1, Col2, Col3, [COUNT]
FROM CTE
试试这个:(在 Oracle 中工作)
WITH ORDERS
AS (SELECT
TO_DATE ( '2013-09-18 00:00:01',
'YYYY-MM-DD HH24:MI:SS' )
AS THE_DATE,
'John' AS NAME
FROM
DUAL
UNION ALL
SELECT
TO_DATE ( '2013-09-19 00:00:01',
'YYYY-MM-DD HH24:MI:SS' )
AS THE_DATE,
'James' AS NAME
FROM
DUAL
UNION ALL
SELECT
TO_DATE ( '2013-09-20 00:00:01',
'YYYY-MM-DD HH24:MI:SS' )
AS THE_DATE,
'John' AS NAME
FROM
DUAL
UNION ALL
SELECT
TO_DATE ( '2013-09-20 00:00:02',
'YYYY-MM-DD HH24:MI:SS' )
AS THE_DATE,
'John' AS NAME
FROM
DUAL
UNION ALL
SELECT
TO_DATE ( '2013-09-20 00:00:03',
'YYYY-MM-DD HH24:MI:SS' )
AS THE_DATE,
'John' AS NAME
FROM
DUAL
UNION ALL
SELECT
TO_DATE ( '2013-09-20 00:00:04',
'YYYY-MM-DD HH24:MI:SS' )
AS THE_DATE,
'John' AS NAME
FROM
DUAL
UNION ALL
SELECT
TO_DATE ( '2013-09-21 16:00:01',
'YYYY-MM-DD HH24:MI:SS' )
AS THE_DATE,
'Jennifer' AS NAME
FROM
DUAL)
SELECT
THE_DATE,
NAME,
ROWNUM
FROM
(SELECT
TRUNC ( THE_DATE ) THE_DATE,
NAME,
COUNT ( 1 )
FROM
ORDERS
GROUP BY
TRUNC ( THE_DATE ),
NAME);
原始数据:
9/18/2013 12:00:01 AM John
9/19/2013 12:00:01 AM James
9/20/2013 12:00:01 AM John
9/20/2013 12:00:02 AM John
9/20/2013 12:00:03 AM John
9/20/2013 12:00:04 AM John
9/21/2013 4:00:01 PM Jennifer
结果:
9/21/2013 Jennifer 1
9/19/2013 James 2
9/20/2013 John 3
9/18/2013 John 4
您可以使用该ROW_NUMBER()
功能。
例如
WITH q AS (
SELECT field_a
FROM SomeTable
GROUP BY field_a
)
SELECT ROW_NUMBER() OVER(ORDER BY field_a) AS row_num,
field_a
FROM q
您可以尝试SELECT INTO
使用IDENTITY
列。这将创建新的临时表#GrupTOT
。
这是一个小提琴示例。
SELECT SeqNo = identity(int,1,1), --Identity column
AY = J.AY
BLK = J.BLK,
DRE = J.DRE,
TOT = SUM(J.BORÇ)
INTO #GrupTOT
FROM #TümDATA J
GROUP BY J.AY, J.BLK, J.DRE;
--SELECT * FROM #GrupTOT