Home > Back-end >  how to get flags based on app code and year
how to get flags based on app code and year

Time:10-07

below is the given table in DB

ID org_id app_code year
1 205 EBB 2016
2 205 EBB 2016
3 205 LF 2017
4 205 LF 2017
5 205 LF 2018
6 205 LF 2018
7 205 LF 2019
8 205 LF 2019
9 205 EBB 2020
10 205 EBB 2020
11 205 LF 2020
12 205 LF 2020
13 205 EBB 2021
14 205 EBB 2021
15 205 LF 2021
16 205 LF 2021
17 205 LF 2022
18 205 LF 2022
19 205 EBB 2022
20 205 EBB 2022

expected output is

ID org_id app_code year Flag
1 205 EBB 2016 2
2 205 EBB 2016 2
3 205 LF 2017 1
4 205 LF 2017 1
5 205 LF 2018 1
6 205 LF 2018 1
7 205 LF 2019 1
8 205 LF 2019 1
9 205 EBB 2020 3
10 205 EBB 2020 3
11 205 LF 2020 3
12 205 LF 2020 3
13 205 EBB 2021 3
14 205 EBB 2021 3
15 205 LF 2021 3
16 205 LF 2021 3
17 205 LF 2022 3
18 205 LF 2022 3
19 205 EBB 2022 3
20 205 EBB 2022 3

if ALL the app code for a particular year is LF then 1

if ALL the app code for a particular year is EBB the 2

if the app code for a particular year having both LF and EBB the 3.

need help in SQL

CodePudding user response:

To calculate flags for each year and org_id separately you can use following query:

SELECT *,
MAX(CASE WHEN app_code='EBB' THEN 2 ELSE 0 END) OVER (PARTITION BY org_id, year)  
MAX(CASE WHEN app_code='LF' THEN 1 ELSE 0 END) OVER (PARTITION BY org_id, year) Flag
FROM T

If version < 8.0 you can use more complex query:

SELECT T.*, F.Flag
FROM T
JOIN (
  SELECT org_id, year, CASE WHEN IsEBB=1 AND IsLF=1 THEN 3 WHEN IsEBB=1 THEN 2 ELSE 1 END Flag
    FROM (
      SELECT org_id, year, MAX(CASE app_code WHEN 'EBB' then 1 END) IsEBB, MAX(CASE app_code WHEN 'LF' then 1 END) IsLF
      FROM T
    GROUP BY org_id, year
  ) Group1
) F ON T.org_id=F.org_id AND T.year=F.year

CodePudding user response:

You can do this with CASE.

SELECT
ID
,org_id
,app_code
,year
,CASE WHEN app_code = 'EBB' AND year = 2016 THEN 2
      WHEN app_code = 'LF' AND year = 2017 THEN 1
  --add other conditions here
 END AS Flag

FROM
tbl_name
  • Related