我有一个包含很多行的临时表(#TümDATA)。我INSERT
将行放入另一个带有GROUP BY
子句的临时表(#GrupTOT)中。但我被困在这里,我需要在它们被GROUPED后给行一个连续的数字。
这是我的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
答案 0 :(得分:0)
您可以使用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
答案 1 :(得分:0)
试试这个:(在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
答案 2 :(得分:0)
您可以使用ROW_NUMBER()
功能。
E.g。
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
答案 3 :(得分:0)
您可以使用SELECT INTO
列尝试IDENTITY
。这将创建新的临时表#GrupTOT
。
这是 Fiddle example 。
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