Row_number函数sql

时间:2016-08-22 07:01:50

标签: sql sql-server

如何编写查询,以便按照屏幕截图所示进行操作。

我使用row_number函数创建ID

Select  ROW_NUMBER () over (Partition by R.BrandName, R.City order by R.City, R.BrandName) as ID,

query result

3 个答案:

答案 0 :(得分:0)

试试这个:

Select  
   ROW_NUMBER () over (Partition by R.BrandName,R.Description,R.City order by R.ProdDateTime DESC) as ID,
   R.BrandName,
   R.Description,
   R.City 
FROM Table R

答案 1 :(得分:0)

什么是FACode?似乎你想通过BrandName进行分区。试试这个:

ROW_NUMBER () over (Partition by BrandName order by R.City) as ID

答案 2 :(得分:0)

我认为你需要通过加工行来完成,并且必须以增量顺序给出相同的数字..如果是这样的话,请使用dense_rank()而不是row_number()。

尝试使用以下脚本..

--creating a sample table
CREATE TABLE dbo.GroupSet
(ProdDateTime DATETIME,
 BrandName VARCHAR(50),
 [Description]  VARCHAR(50),
 City VARCHAR(10))

 --populatinng data
 INSERT INTO GroupSet
 VALUES  ('2016-06-15 16:10:03.000','13856.11','POL','Ak')
         ,('2016-06-15 14:56:05.000','13856.11','POL','Ak')
         ,('2016-06-15 15:58:22.000','13856.11','POL','Ak')
         ,('2016-05-04 01:02:50.000','30205.18','MUR','Ak')
         ,('2016-05-03 02:15:10.000','30205.18','MUR','Ak')
         ,('2016-05-03 04:23:10.000','30205.18','MUR','Ak')
         ,('2016-05-03 03:32:10.000','30205.18','MUR','Ak')
         ,('2016-06-03 15:31:20.000','30205.18','MUR','Ak')

--Here is the script and the result you wanted to be in the column ID_DenseRank
SELECT  
   ROW_NUMBER () over ( PARTITION BY R.BrandName, R.City order by R.City, R.BrandName) as ID_RNO, -- ROW_NUMBER() result
   DENSE_RANK() over ( order by  R.BrandName, R.City ) as ID_DenseRank, -- DENSE_RANK() result
   R.ProdDateTime,
   R.BrandName,
   R.[Description],
   R.City 
FROM GroupSet R