Ordered Value by Column / Row

后端 未结 4 983
借酒劲吻你
借酒劲吻你 2021-01-16 15:24

Its a little difficult to explain. It might be easier to skip to the examples.

A table has an id and four columns that each allow null.

ID, Col1, Co         


        
4条回答
  •  长情又很酷
    2021-01-16 15:58

    I may not understand everything that you described you wanted. From reading your problem and comments from others, I am guessing that this is what you are looking for:

    Updated version:

    with cteOriginal as
    (
        select *, RANK() over (partition by [SortOrder] order by id asc) as [NonUniqueSortOrder]
        from
        (
            select id, A as [value], 1 as [SortOrder]
            from #original
            where A is not null
            union all
            select id, B as [value], 2 as [SortOrder]
            from #original
            where B is not null
            union all
            select id, C as [value], 3 as [SortOrder]
            from #original
            where C is not null
            union all
            select id, D as [value], 4 as [SortOrder]
            from #original
            where D is not null
        ) as temp
    )
    select [value]
    from cteOriginal
    where id = (select MIN(tmp.id) from cteOriginal tmp where tmp.value = cteOriginal.value)
    order by ((([NonUniqueSortOrder] - 1) * 4) + [SortOrder])
    

    I got rid of the duplicate values by picking the one with the smallest id, min(id). You can change it to use max(id).

    Initial version:

    with cteOriginal as
    (
        select *, RANK() over (partition by [column] order by id asc) as [NonUniqueSortOrder]
        from
        (
            select id, A as [value], 'A' as [Column], 1 as [SortOrder]
            from #original
            where A is not null
            union all
            select id, B as [value], 'B' as [Column], 2 as [SortOrder]
            from #original
            where B is not null
            union all
            select id, C as [value], 'C' as [Column], 3 as [SortOrder]
            from #original
            where C is not null
            union all
            select id, D as [value], 'D' as [Column], 4 as [SortOrder]
            from #original
            where D is not null
        ) as temp
    )
    select [value]
    from cteOriginal
    order by ((([NonUniqueSortOrder] - 1) * 4) + [SortOrder])
    

    By the way, I am using mssql 2005 for this query. Please comment and we'll refine it.

提交回复
热议问题