Sql server中的循环短路

时间:2014-11-22 17:58:20

标签: sql-server

我有一个带有以下详细信息的SQL Server表

  

Cleint_ID Photo_Rank
2 1   1 9
3 7
  1 6
1 5
  1 7
3 8
  3 5
1 4
  2 3
2 2
  1 9
3 7

现在我想安排所有照片,以便所有客户的第一张照片将显示排名最高的排名然后是所有客户的第二高排名照片

我想要结果

  

如果发现,Cleint_ID1的最高照片排名等级为1   如果找到,Cleint_ID2的最高照片排名等级为2   如果发现,Cleint_ID3的最高照片排名等级为3   Cleint_ID1第二高的照片等级为1   发现
Cleint_ID2第二高的照片排名为2   如果发现
Cleint_ID3第二高的照片排名   如果发现则为3

并继续

![http://www.impressivefm.com/one.png]

3 个答案:

答案 0 :(得分:0)

似乎可以使用RANK函数,如下所示:

select Client_id, photo_rank, rank_ordinal
from (select Client_ID, photo_rank,
        RANK() over (PARTITION BY Client_ID ORDER BY Photo_Rank) as rank_ordinal
    from TableName) _
order by rank_ordinal, client_id

答案 1 :(得分:0)

试试这个:

您可以使用 Max with Partition BY Clause 这为分区分区中的最大值提供了

select 'Client_ID' +CAST(Client_ID as VARCHAR(10)) as Client_ID ,
MAX(Photo_rank) as MaxRank from 
(
select MAX(Photo_rank) over(partition by Client_ID )as RN ,*
 from Mytable)D
 group by  Client_ID

<强>输出

Client_ID   MaxRank 
Client_ID1  9
Client_ID2  3
Client_ID3  8

答案 2 :(得分:0)

  1. 使用DISTINCT CLIENT_ID创建#TEMP
  2. 使用3个最高的Photo_Rank
  3. 创建#ID_LIST
  4. 使用CURSOR构建最终表
  5. &#13;
    &#13;
    --CREATE TABLE #TEMP (Cleint_ID INT)
    --CREATE TABLE #ID_LIST (ID int IDENTITY(1,1)  ,Cleint_ID INT,Photo_Rank INT)
    INSERT INTO #TEMP (Cleint_ID )
    SELECT DISTINCT Cleint_ID
    FROM [SCORE]
    DECLARE cur cursor FAST_FORWARD READ_ONLY
    FOR
     SELECT  Cleint_ID
     FROM #TEMP
    DECLARE @d INT
    OPEN cur
     FETCH NEXT FROM cur INTO @d
     WHILE @@FETCH_STATUS=0
     BEGIN 
    INSERT INTO #ID_LIST (Cleint_ID,Photo_Rank)
    SELECT DISTINCT TOP 3  Cleint_ID,Photo_Rank
     FROM [SCORE]  
    WHERE Cleint_ID =@D
    ORDER BY Cleint_ID,Photo_Rank DESC
    FETCH NEXT FROM cur  INTO @d
    END
    Close  cur 
    DEALLOCATE cur
    --TRUNCATE TABLE #TEMP
    --TRUNCATE TABLE #ID_LIST
    DECLARE @TBL TABLE (Cleint_ID INT,Photo_Rank INT)
    DECLARE @ID INT=-2 
    DECLARE @X INT=(SELECT COUNT(*) FROM #TEMP)
    WHILE @X!=0 
    BEGIN
    WHILE @ID<=(SELECT COUNT(*) FROM #ID_LIST)
    BEGIN
    INSERT INTO @TBL
    SELECT DISTINCT Cleint_ID,Photo_Rank FROM #ID_LIST
    WHERE ID=@ID+3
    SET @ID=@ID+3
    END
    SET @X=@X-1
    SET @ID=@ID-11
    PRINT @ID
    END
    SELECT * FROM @TBL
    &#13;
    &#13;
    &#13;

    enter image description here