Is there any way to generate Alphabetic Sequence with Current Year In SQL

拥有回忆 提交于 2021-01-05 08:58:23

问题


How can we write a SQL function which can generate 'Sequence_Code' like AA,AB,AC....AZ. BA,BB,BC.... with the combination of last two digit of 'Current_Year' for each 'ID'. Order by 'Record_Date'

For instance: If Current_Year of First row is is 2019, then Sequence_Code should be 19AA. My table is LoadData

Sequence_Code ID Current_Year Record_Date
NULL 310001 2019 2019-01-01
NULL 310002 2018 2018-02-22
NULL 310003 2020 2020-02-20
NULL 310004 2020 2020-02-10

Expected Output is:

Sequence_Code ID Current_Year Record_Date
19AA 310001 2019 2019-01-01
18AB 310002 2018 2018-02-22
20AC 310003 2020 2020-02-20
20AD 310004 2020 2020-02-10

回答1:


With ROW_NUMBER() window function and math:

WITH cte AS (SELECT *, ROW_NUMBER() OVER (ORDER BY Record_Date) rn FROM LoadData)
SELECT RIGHT(Current_Year, 2) + 
       CHAR(ASCII('A') + rn / 26 + CASE rn % 26 WHEN 0 THEN -1 ELSE 0 END) + 
       CHAR(ASCII('A') - 1 + CASE rn % 26 WHEN 0 THEN 26 ELSE rn % 26 END) Sequence_Code,
       ID, Current_Year, Record_Date
FROM cte
ORDER BY rn

If you want to update the column Sequence_Code of the table:

WITH cte AS (SELECT *, ROW_NUMBER() OVER (ORDER BY Record_Date) rn FROM LoadData)
UPDATE cte
SET Sequence_Code = RIGHT(Current_Year, 2) + 
                    CHAR(ASCII('A') + rn / 26 + CASE rn % 26 WHEN 0 THEN -1 ELSE 0 END) + 
                    CHAR(ASCII('A') - 1 + CASE rn % 26 WHEN 0 THEN 26 ELSE rn % 26 END)

See the demo.
Results:

> Sequence_Code |     ID | Current_Year | Record_Date
> :------------ | -----: | -----------: | :----------
> 18AA          | 310001 |         2018 | 2018-01-01 
> 19AB          | 310002 |         2019 | 2019-02-22 
> 20AC          | 310004 |         2020 | 2020-02-10 
> 20AD          | 310003 |         2020 | 2020-02-20 



回答2:


The simplest method might be to generate all combinations and enumerate them:

with alpha as (
      select 'A' as alpha union all
      select 'B' as alpha union all
      . . .  -- continue for the rest of the letters
      select 'Z' as alpha
     ),
     alphas as (
      select concat(a1.alpha, a2.alpha) as alpha2,
             row_number() over (order by a1.alpha, a2.alpha) as seqnum
      from alpha a1 cross join
           alpha a2
     )
select current_year || alpha2.alpha2 as sequence_code, t.*
from (select t.*,
             row_number() over (partition by current_year order by record_date) as seqnum
      from LoadData t
     ) t left join
     alpha2 
     on t.seqnum = a2.seqnum;

Note: This uses standard SQL, so the functionality may have different syntax depending on the database.



来源:https://stackoverflow.com/questions/65494479/is-there-any-way-to-generate-alphabetic-sequence-with-current-year-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!