SQL Server In sorted table, how many records in end of result are equals to the last item

zpqajqem  于 2023-04-28  发布在  其他
关注(0)|答案(3)|浏览(102)

I have a Table with Sort and Status fields.
I need to create a Query with 2 fields: LastStatus and Times .
First field shows (sorting per Sort) the status of last record. The second shows how many records, in end of table, has the same value.

Example

When the query result is this:
| Sort | Status |
| ------------ | ------------ |
| 1 | alpha |
| 2 | bravo |
| 3 | charlie |
| 4 | alpha |
| 5 | alpha |
| 6 | charlie |
| 7 | alpha |
| 8 | alpha |
| 9 | alpha |

Expected result:

LastStatusTimes
alpha3

Thanks!

xwbd5t1u

xwbd5t1u1#

On second read, it is more of a Gaps-and-Islands problem

Example or dbFiddle

with cte as (
Select [Sort]
      ,[Status]
      ,Grp = row_number() over (order by Sort)
            -row_number() over (partition by [Status] order by Sort)
 From YourTable
 )
 Select top 1 
        [Status]
       ,Times = sum(1)
  From  cte
  Group By Grp,[Status]
  Order by max([Sort]) desc

Results

Status  Times
alpha   3
hfwmuf9z

hfwmuf9z2#

you can use window function(lead and First_value for find Times

select Status LastStatus,times
from (
        select 
              Status
            ,lastvalue- First_value(sort) over(order by  lg desc   ) +1  
            as times
            ,sort
             ,row_number() over (order by Sort desc) as rw
        from (
                select *,

                    max(Sort) over (order by Sort desc) as lastvalue,
                    Last_value(Status) over (order by Sort desc) as lastStatus,

                     case when 
                     lead(Status) over(order by sort desc)!=Status then 1 else 0 end as lg
                 from L
        )a
        where lg=1
    
)a
where rw=1
zlhcx6iw

zlhcx6iw3#

The solution below gets the number of the last row in the last sequence of the Status value using only descending sort.

SELECT TOP 1
  [status] AS [LastStatus],
  ROW_NUMBER() OVER (ORDER BY [Sort] DESC) AS [Times]
FROM t
ORDER BY
  ROW_NUMBER() OVER (ORDER BY [Sort] DESC) 
    - ROW_NUMBER() OVER (PARTITION BY [Status] ORDER BY [Sort] DESC),
  [Times] DESC

db<>fiddle

相关问题