为所有分区记录分配唯一的ROW NUMBER()

时间:2015-08-24 09:03:53

标签: sql sql-server window-functions

在这个查询中,它是对记录进行分区但是我需要为所有结果集分配行号,不应该重复行号,每行应该是唯一的fpr。有人帮忙吗?提前谢谢。

select *
from Store  
order by 
   row_number() over (partition by category order by storename),category

SQLFIDDLE中的表cloumn示例: http://sqlfiddle.com/#!6/767ab/86

我希望输出格式为:

RowNo     Category  
1         Fruits
2         Chocs
3         Vegetables
4         Fruits
5         Chocs
6         Vegetables
..........

5 个答案:

答案 0 :(得分:0)

如果您只想提供唯一的行号,请不要仅按顺序使用分区 请尝试以下查询。

select *,row_number() over (order by storename) As RowNumber
from Store  
order by 
   row_number() over (order by storename),Category

答案 1 :(得分:0)

不要使用分区条款

select *
from Store  
order by 
   row_number() over (order by storename),category

Demo Fiddle

答案 2 :(得分:0)

     select * into #temp
     from(
        select *,
        ROW_NUMBER() OVER(Partition by Category ORDER BY Category) AS Row_Number
        from Store) x  



     select ROW_NUMBER,StoreName,Category,Price,Quantity,
     ROW_NUMBER() over (order by ROW_NUMBER,category)  as uniquerownum from #temp
     group by Row_Number,StoreName,Category,Price,Quantity 

样品: -

http://sqlfiddle.com/#!6/767ab/138

放轻松......

答案 3 :(得分:0)

尝试这样的事情:

WITH data AS (
    SELECT  ROW_NUMBER() OVER (PARTITION BY Category ORDER BY Category) rn, *
    FROM    STORE
)
SELECT  ROW_NUMBER() OVER (ORDER BY rn, Category) rn ,
        StoreId ,
        StoreName ,
        Category ,
        Price ,
        Quantity ,
        Address 
FROM    data
ORDER BY 1

这产生以下顺序:

1   CHOCOS
2   FRUITS
3   ICECREAM
4   VEGETABLES
5   CHOCOS
6   FRUITS
7   ICECREAM
8   VEGETABLES
9   CHOCOS
10  FRUITS

答案 4 :(得分:-1)

$this->email->to('one@example.com, two@example.com, three@example.com');