简体   繁体   English

从 CTE 中的 select 语句中的 case 中获取值的 Sql 查询

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

I am trying to write a SQL.我正在尝试编写 SQL。 In this, I want columns Bank, and Y-Bank in the output.在此,我希望输出中的列 Bank 和 Y-Bank。 Y-Bank is being calculated based on certain case statements, using CTE, but I am not able to return Y-Plant as the column. Y-Bank 是根据某些案例陈述计算的,使用 CTE,但我无法将 Y-Plant 作为列返回。

这是样本输入和输出

I also created a table as shown in the input/output here: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=749e4ca1570880e9c64c4553d18dea1a我还创建了一个表,如此处的输入/输出所示: 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.如果我理解正确,您想计算每个银行的“Y”值的数量。 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. 是一个 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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