简体   繁体   中英

PL SQL - How to use select statement inside for loop with conditional return?

This is PL SQL for an Oracle db. I want to use a for loop to identify items for which there is no forecast (value of 0) at some stores but some forecast at others (value greater than 0). The easiest way seems to first select distinct items. Then for each item, identify using conditions if there are some stores with AND some stores without forecast.

All of this data is on one table, ie the forecast of each item at each store. I have never structured a PLSQL for loop. Could you help me structure this in PL SQL? Do I have to use a stored procedure? The pseudo code would look like this:


FOR i IN (SELECT DISTINCT Item FROM TABLE)
  IF 
     ( ( SELECT COUNT(*) WHERE Forecast = 0 ) > 0
   AND ( SELECT COUNT(*) WHERE Forecast > 0 ) > 0
  THEN
     PRINT Item Name
End Loop

Thank you!

You can use single query to fetch such item as following:

Select item
From table
Group by item
Having (sum(case when forecast = 0 
then 1 end) > 0
And sum(case when forecast > 0 
then 1 end) > 0)

If you want it to use in for loop then following should be the approach:

SET SERVEROUT ON
Begin
For i in (Select item
    From table
    Group by item
    Having (sum(case when forecast = 0 
    then 1 end) > 0
    And sum(case when forecast > 0 
    then 1 end) > 0))
Loop
DBMS_OUTPUT.PUT_LINE(I.ITEM);
End loop;

End;
/

Cheers!!

I think you can do what you want with an aggregation query. Assuming forecasts are never negative, you can get the items with both zero and non-zero forecast values with:

select item
from forecasts
group by item
having min(forecast) = 0 and max(forecast) > 0;

You can, of course, put this in a loop to "print" out the values. I don't see the value in doing that, unless you are committed to PL/SQL code for some other reason.

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