我有两张桌子可供使用。第一个表#CustomerList
我用值手动初始化。然后我创建了第二个表#CustomerListWithRank_Id
,该表基于第一个表#CustomerList
。
第一个表和第二个表之间的唯一不同之处在于,第二个表#CustomerListWithRank_Id
有一个列,它为每行提供了当我遍历该表时我在SQL代码中进一步使用的rownumber
所以我遇到的问题是我只想用[FileName]列中的唯一值来初始化#CustomerListWithRank_Id
,我该怎么做?
SELECT '3004' Customer_No,'831001' DDD_Reference_No,'varer831.csv' [FileName]
INTO #CustomerList -- DROP TABLE #CustomerList
UNION ALL SELECT '3002' Customer_No,'199001' DDD_Reference_No,'varer199.csv' [FileName]
UNION ALL SELECT '3003' Customer_No,'199002' DDD_Reference_No,'varer199.csv' [FileName]
-
SELECT *, ROW_NUMBER() OVER (ORDER BY Customer_No) AS 'Rank_Id'
INTO #CustomerListWithRank_Id --DROP TABLE #CUstomerListWithRank_ID
FROM #CustomerList
如果我在上面的查询中使用GROUP BY [FileName],我会收到此错误:
Msg 8120, Level 16, State 1, Line 1
Column '#CustomerList.Customer_No' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
答案 0 :(得分:1)
这是你需要的吗?
select *, ROW_NUMBER() OVER (ORDER BY Customer_No) AS 'Rank_Id'
INTO #CustomerListWithRank_Id
from
(
SELECT max(Customer_No) Customer_No, max(DDD_Reference_No) DDD_Reference_No, FileName
FROM #CustomerList
group by FileName
) t
答案 1 :(得分:0)
这就是你需要的
SELECT * INTO #CustomerListWithRank_Id From
(SELECT *, ROW_NUMBER() OVER (PARTITION BY FileName Order by Customer_No) AS RowNum FROM CustomerList)