简体   繁体   中英

Sql query on taking the value from a case within select statement in a CTE

I am trying to write a SQL. In this, I want columns Bank, and Y-Bank in the output. Y-Bank is being calculated based on certain case statements, using CTE, but I am not able to return Y-Plant as the column.

这是样本输入和输出

I also created a table as shown in the input/output here: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=749e4ca1570880e9c64c4553d18dea1a

Below is the code:

WITH CTE AS
(
SELECT
"BANK",
(select 
case 
when "TEST"=0 AND "TEST1">0
THEN ( SELECT COUNT("ZONES")FROM mytable I WHERE  I.BANK = O.BANK AND I."ZONES"='Y' )
END AS "Y-BANK"
from(
  
 (SELECT  
         
          CASE WHEN ( (SELECT COUNT("ZONES")FROM mytable I WHERE I.BINDER = O.BINDER AND I."ZONES"='N' ) = 0 ) AND ( (SELECT COUNT("ZONES")FROM mytable I WHERE I.BINDER = O.BINDER AND I."ZONES"='Y' ) > 0 )
    THEN ( SELECT COUNT("ZONES")FROM mytable I WHERE  I."TOTAL LINE"= O."TOTAL LINE"AND I."ZONES"='N' )
  END AS "TEST",
          CASE WHEN ( (SELECT COUNT("ZONES")FROM mytable I WHERE I.BINDER = O.BINDER AND I."ZONES"='' ) = 0 ) AND ( (SELECT COUNT("ZONES")FROM mytable I WHERE I.BINDER = O.BINDER AND I."ZONES"='Y' ) > 0 )
       THEN ( SELECT COUNT("ZONES")FROM mytable I WHERE  I."TOTAL LINE" = O."TOTAL LINE" AND I."ZONES"='Y' )
  END AS "TEST1"
  from mytable )
  )
  )
FROM mytable O
)
 


SELECT *
FROM CTE O

Can someone help me out on how can I correct it?

If I understand correctly, you want to count the number of "Y" values for each bank. You can use a window function:

select t1.*, sum(zones = 'Y') over (partition by Bank1) as y_bank
from t1

Here is a db<>fiddle.

you can use following query

select 
   bank1 as "bank",
   (select count(*)over(partition by Bank1,Zones order by Bank1 desc) as "y_bank" from t1 where Zones = 'Y' and Bank1 = t.Bank1 limit 1) as "y_bank"
from t1 t

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM