Query help....three conditions

Hi All,
I have a table with the following data
empno emptype empstatus
1     best     Active
2     good     drop
3     best     Active
1     good     cancel
4     good     left
5
This table consists of three columns
Emptype has two distinct values - good,best
Empstatus consists of one status - Active for best type
Empstatus consists of three status - Drop,cancel,left for good type.
One emp can get either any one of these three status in good type
The highest level of type is best followed by good
An emp can get both the types
I need to get the highest level of status achieved so far for an emp
For example, emp 1 has got both best and good types
Then the output for emp 1 will be
empno higheststatus
1     Active
If the emp didnot get any, it should display NULL.
The output for the above data should be
empno higheststatus
1     Active
2     drop
3     Active
4     left
5     
Thank u for ur help !!

880186 wrote:
Hi Frank,
thank you for the logic....
But the data is not showing up correctly... its not showing any of cancel or left empstatusYou said you would accept any of the 3:
if an empno consists of only emptype as good then the higheststatus is any of the three - drop,cancel,leftIf you'd rather have 'cancel', then use 'cancel'. If you'd rather have 'left', then use 'left'. If you want 'cancel' sometimes, and 'drop' at other times, and 'left' at other times, explain how you decide which one you want. If you can say it in English, someone will help you do it in SQL.
nly the higheststatus is showing up as Active/ drop.....Point out exactly where the query I posted is giving the wrong results, and explain how you get the right results in those places.
Also, I couldn't understand it exactly...
What does max function do here ?
,       CASE
           WHEN  COUNT (DISTINCT emptype) = 2
                    THEN  'Active'
           WHEN  MAX (emptype) = 'best'
                    THEN  'good'
           WHEN  MAX (emptype) = 'good'
                    THEN  'drop'  -- or 'cancel', or 'left'
       END         AS highestempstatusYou said there were only 2 possible values for emptype: 'best' and 'good'. The requirements you posted were
If an empno consists of both emptype, then the higheststatus is Active
If an empno consists of only emptype as best then the higheststatus is good
if an empno consists of only emptype as good then the higheststatus is any of the three - drop,cancel,left
if an empno consists of none empstatus, the it will be blankThe CASE expression above does that, in that order. By the time the second WHEN clause
WHEN  MAX (emptype) = 'best'is evaluated, we know that there are not 2 distinct emptypes present for this empno. 2 is the maximum number possible, so, if there are not 2 distinct values, there must be 1 or 0 dstinct values. The next 2 WHEN clauses test whether there is 1 value for emptype. If there are 0 values, then MAX will return NULL, and the WHEN clause will not be TRUE. If there is 1 value of emptype, then MAX will return that value. (MIN will also return that value; it doesn't matter if you use MIN or MAX in this case.)

Similar Messages

  • Running Query Based on Condition

    Hi
    I want to run different query based on a condition. I am not able to execute the following query. is this the right way to run different query based on condition?
    SELECT * FROM (
    CASE WHEN (SELECT COUNT (*) from data1 where ID = 1 AND stype = 'A') > 0 THEN select * from data where ID = 1 AND stype = 'A'
    WHEN (SELECT COUNT (*) from data1 where ID = 1 AND stype = 'B') > 0 THEN select * from data where ID = 1 AND stype = 'B'
    WHEN (SELECT COUNT (*) from data1 where ID = 1 AND stype = 'C') > 0 THEN select * from data where ID = 1 AND stype = 'C'
    END
    ) as a;
    Edited by: user6016744 on 21 Apr, 2011 12:40 AM

    This works for us; hope it helps.
    CREATE OR REPLACE FUNCTION SCHEMA.GET_STEP_COST (loan_number_in in VARCHAR2, step_code_in in VARCHAR2 default null, ws_in in VARCHAR2 default null )
    RETURN VARCHAR2 IS retval  VARCHAR2 (50);
    /*passing in loan number and step code you need the cost for, will return the cost*/
    BEGIN
        CASE ws_in --depending on workstation in is the table select
        WHEN 'F' THEN
            EXECUTE IMMEDIATE 'SELECT '|| step_code_in ||' FROM CLAIMS_FCL_STEPS WHERE LOAN_NUMBER = '|| loan_number_in ||'' INTO retval;
        WHEN 'R' THEN
           EXECUTE IMMEDIATE 'SELECT '|| step_code_in ||' FROM CLAIMS_RS_STEPS  WHERE LOAN_NUMBER = '|| loan_number_in ||'' INTO retval;
        WHEN 'L' THEN
           EXECUTE IMMEDIATE 'SELECT '|| step_code_in ||' FROM CLAIMS_LM_STEPS  WHERE LOAN_NUMBER = '|| loan_number_in ||'' INTO retval;   
        ELSE
            retval := 0;
        END CASE;
      RETURN retval;
    END GET_STEP_COST;
    /

  • Query Help-2

    Query Help:
    http://forum.java.sun.com/thread.jsp?forum=45&thread=471180&tstart=15&trange=15
    It seems I have confused enough people with my improper presentation of query. Sorry guys. I will restate my question with different table names.
    The above was my previous posting, which was not clear..so Iam restating my problem as follows....
    I have the following tables
    Customer(custID, Name, Address)
    Order(custID, OrderID, orderDate)
    CreditCard(custID, creditCard#, creditCardType)
    Now if I have 3 records in Order with custID 100 and 2 records in CreditCard as
    Order:
    100,A001,11/22/03
    100,A002,11/24/03
    100,A003,12/02/03
    CreditCard:
    100,42323232..., VISA
    100,5234234...., MASTER
    Now how can I get
    custID, Name, Address, OrderID, orderDate, creditCard#, creditCarType
    data in minimum no. of records....
    I think I have made my query clear..
    now please help me guys...
    thanks so much for your help.

    You are right.
    But frankly the actual tables on my database are not customer,orders and creditcards..but I just tried to reproduce the problem with these tables, please ignore that user needs a refund etc situtaion. If the tables were actually order,creditcards etc..it would have been a problem to be considered.
    Can you please help me with the query
    if I have m rows in Order and n rows in CreditCard. I will get m*n records, I looking for max(m,n).
    With the following fields in my query result,
    custID, Name, Address, OrderID, orderDate, creditCard#, creditCarType
    from Customer, Order, CreditCard tables
    Thanks so much for your htlp

  • SQL Query Help - Is this possible or impossible????

    Hi guys,
    I need help with an SQL query that I'm trying to develop. It's very easy to explain but when trying to implement it, I'm struggling to achieve the results that I want.....
    For example,
    I have 2 tables
    The first table is:
    1) COMPANY create table company (manufacturer varchar2(25),
                                                          date_established date,
                                                          location varchar2(25) );My sample test date is:
    insert into company values ('Ford', 1902, 'USA');
    insert into company values ('BMW', 1910, 'Germany');
    insert into company values ('Tata', 1922, 'India');The second table is:
    2) MODELS create table models (manufacturer varchar(25),
                                                 model varchar2(25),
                                                 price number(10),
                                                 year date,
                                                 current_production_status varchar2(1) ) ;My sample test data is:
    insert into models values ('Ford', 'Mondeo', 10000, 2010, 0);
    insert into models values ('Ford', 'Galaxy', 12000,   2008, 0);
    insert into models values ('Ford', 'Escort', 10000, 1992, 1);
    insert into models values ('BMW', '318', 17500, 2010, 0);
    insert into models values ('BMW', '535d', 32000,   2006, 0);
    insert into models values ('BMW', 'Z4', 10000, 1992, 0);
    insert into models values ('Tata', 'Safari', 4000, 1999, 0);
    insert into models values ('Tata', 'Sumo', 5500,   1996, 1);
    insert into models values ('Tata', 'Maruti', 3500, 1998, 0);And this is my query:
    SELECT
            com.manufacturer,
            com.date_established,
            com.location,
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.model),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.price),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.year),
            mod.current_production_status
    FROM
           company com,
           models mod
    WHERE
          mod.manufacturer = com.manufacturer
          and com.manufacturer IN ('Ford', 'BMW', 'Tata')
          and mod.current_production_status IN (1,0)
    ORDER BY
            mod.current_production_status DESCWhat I want the query to output is this:
    com.manufacturer        com.date_established          com.location          mod.model          mod.price             mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    BMW               1910                    Germany               -               -               -          0
    Tata               1922                    India               Sumo               5500               1998          1If current_production_status is 1 it means this particular model has been discontinued
    If current_production_status is 0 it means the manufacturer does not have any discontinued models and all are in procuction.
    The rule is only one record per manufacturer is allowed to have a current_production_status of 1 (so only one model from the selection the manufactuer offers is allowed to be discontinued).
    So the query should output the one row where current_production_status is 1 for each manufacturer.
    If for a given manufacturer there are no discontinued models and all have a current_production_status of 0 then ouput a SINGLE row that only includes the data from the COMPANY table (as above). The rest of the columns from the MODELS table should be populated with a '-' (hyphen).
    My query as it is above will output all the records where current status is 1 or 0 like this
    com.manufacturer        com.date_established          com.location          mod.model          mod.price          mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    Tata               1922                    India               Sumo               5500               1998          1
    Ford               1902                    USA               -               -               -          0                    
    Ford               1902                    USA               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    Tata               1922                    India               -               -               -          0
    Tata               1922                    India               -               -               -          0However this is not what I want.
    Any ideas how I can achieve the result I need?
    Thanks!
    P.S. Database version is '10.2.0.1.0'

    Hi Vishnu,
    Karthiks query helped...
    But this is the problem I am facing...
    SELECT
            com.manufacturer,
            com.date_established,
            com.location,
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.model),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.price),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.year),
            mod.current_production_status
    FROM
           company com,
           models mod
    WHERE
          mod.manufacturer = com.manufacturer
          and com.manufacturer = 'Ford'
          and mod.current_production_status IN (1,0)
    ORDER BY
            mod.current_production_status DESCThe value of:
    and com.manufacturer = 'Ford'will be dependent on front end user input....
    When I run the query above I get all the rows where current_production_status is either 1 or 0.
    I only require the rows where current_production_status is 1.
    So if I amend it to look like this:
         and mod.current_production_status = 1This works....
    BUT if a user now passes in more than one manufacturer EG:
    and com.manufacturer IN ('Ford', 'BMW')The query will only return the one row for Ford where current_production_status is 1. However because BMW has no models where current_production_status is 1 (all 3 are 0), I still want this to be output - as one row....
    So like this:
    com.manufacturer        com.date_established          com.location          mod.model          mod.price             mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    BMW               1910                    Germany               -               -               -          0So (hopefully you understand), I want both cases to be catered for.....whether a user enters one manufacturer or more than one...
    Thanks you so much!
    This is really driving me insane :-(

  • SQL Query clauses and conditions

    Hi,
    I wanna to get the entire conditions specified in the SQL query to do a specific treatement on them.
    in fact, i want to do a syntaxical analyse on the query.
    If there is a specific table where query in stored is seperate clauses, objects invoked, conditions used,..., please let me know.
    elsewhere, il you have a PL/SQL program that do that, it'll be wonderfull.
    Best regards;

    thank for your reply, but what i need is not the query text, but the seperated query clauses and conditions.
    best regards

  • Need a query help

    hii
    i need a query help
    i have two tables
    the 1st table will look like this
    associate id weekid no.of. hours
    4000 810 40
    4000 820 30
    4000 830 60
    4000 840 70
    2nd table will look like this
    associate id weekid no.of.hours
    4000 810 40
    4000 820 70
    4000 830 130
    4000 840 200
    so when i subtract the last two records frm each other in the second table the value should be equal to the no.of.hours in the first table.. for example
    the query shud consider the last record and one before the last record and the difference between two records shud be equal to the value in the 1st table
    for example
    consider week id 830 and 840
    in second table 830=130
    840=200
    when u subtraced both values the difference shud be equal to value in the 1st table for tht week id
    1 ---->>>> 840 - 830
    =200 - 130
    =70
    in first table 840 has 70 hrs
    like this it shud check with all records and it shud return only the records which are not equal
    regards
    srikanth

    This..?
    sql>select * from t1;
    A_ID W_ID HRS
    4000  810  40 
    4000  820  30 
    4000  830  60 
    4000  840  70 
    4000  850  80 
    sql>select * from t2;
    A_ID W_ID HRS 
    4000  810  40 
    4000  820  70 
    4000  830  130 
    4000  840  200 
    4000  850  260 
    sql>
    select a_id,w_id,hrs,sum_hrs
    from(
    select t1.a_id a_id,t1.w_id w_id,t1.hrs hrs,t2.hrs sum_hrs,
           t2.hrs - nvl(lag(t2.hrs)  over(order by t1.w_id),0) diff
    from t1,t2
    where t1.w_id = t2.w_id)
    where diff != hrs;
    A_ID W_ID HRS SUM_HRS 
    4000  850  80  260                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Self join sub query help

    This is my table
    Doctor     Appointment Date     Rating
    111     23/12/2009     G1
    111     23/12/2009     G2
    111     23/12/2009     B
    111          23/12/2009 D
    111     23/12/2008     G1
    111          23/12/2008 B
    111     23/12/2007     G2
    111          23/12/2007 B
    111     23/12/2006     D
    For Doctor 111, on a given appointment date he has multiple ratings.
    I have to fetch the rows (with doctor id, appointment date)
    I) which does not have G1 rating but has G2 rating for each appointment date
    And vice versa ( does not have G2 rating but has G1 rating for each appointment date)
    And
    II) if the particular appointment date has both G1 and G2 rating then I can ignore that appointment date – i.e do not fetch any rows if that appointment date has both G1 and G2 ratings.
    And
    III)     if the appointment date has no G1 or G2 rating, then display the appointment date and the doctor.
    So, my result set should have the output from all the three conditions for each doctor.
    I am not sure how it works. I am trying using correlated subqueries any suggestions???

    ME_XE?with data as
      2  (
      3     select 111 as doc_id, to_date('23/12/2009', 'dd/mm/yyyy') as app_date, 'G1'   as app_type from dual union all
      4     select 111 as doc_id, to_date('23/12/2009', 'dd/mm/yyyy') as app_date, 'G2'   as app_type from dual union all
      5     select 111 as doc_id, to_date('23/12/2009', 'dd/mm/yyyy') as app_date, 'B'    as app_type from dual union all
      6     select 111 as doc_id, to_date('23/12/2009', 'dd/mm/yyyy') as app_date, 'D'    as app_type from dual union all
      7     select 111 as doc_id, to_date('23/12/2008', 'dd/mm/yyyy') as app_date, 'G1'   as app_type from dual union all
      8     select 111 as doc_id, to_date('23/12/2008', 'dd/mm/yyyy') as app_date, 'B'    as app_type from dual union all
      9     select 111 as doc_id, to_date('23/12/2007', 'dd/mm/yyyy') as app_date, 'G2'   as app_type from dual union all
    10     select 111 as doc_id, to_date('23/12/2007', 'dd/mm/yyyy') as app_date, 'B'    as app_type from dual union all
    11     select 111 as doc_id, to_date('23/12/2006', 'dd/mm/yyyy') as app_date, 'D'    as app_type from dual
    12  )
    13  select
    14     doc_id,
    15     app_date,
    16     app_type
    17  from
    18  (
    19     select
    20        sum( case when app_type = 'G1' then 1 else 0 end ) over (partition by doc_id, app_date) as g1,
    21        sum( case when app_type = 'G2' then 1 else 0 end ) over (partition by doc_id, app_date) as g2,
    22        doc_id,
    23        app_date,
    24        app_type
    25     from data
    26  )
    27  where g1 = 0 and g2 = 0
    28  or
    29  (
    30     g1 > 0 and g2 = 0
    31  )
    32  or
    33  (
    34     g2 > 0 and g1 = 0
    35  );
                DOC_ID APP_DATE                   APP_TY
                   111 23-DEC-2006 12 00:00       D
                   111 23-DEC-2007 12 00:00       B
                   111 23-DEC-2007 12 00:00       G2
                   111 23-DEC-2008 12 00:00       G1
                   111 23-DEC-2008 12 00:00       B
    5 rows selected.
    Elapsed: 00:00:00.59
    ME_XE?
    ME_XE?select * from v$version;
    BANNER
    Oracle Database 10g Express Edition Release 10.2.0.1.0 - Product
    PL/SQL Release 10.2.0.1.0 - Production
    CORE    10.2.0.1.0      Production
    TNS for Linux: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    5 rows selected.
    Elapsed: 00:00:00.64Is one method using analytics (which allow you to perform operations over a 'window' of data, which seems to be what you need to do).

  • Execute a query to three DB in parallel

    Hi,
    I would like to execute a query to three external servers in parallel in order to obtain the result of an SQL query.
    The result I want to obtain is a list of objects which pertain to a user. This user may have objects in one, two, or three databases.
    The way of doing it should not consume too much memory. I'm using Java mobile and have limitated memory.
    Could you please tell me what's the better way of doing this? Can you provide an example?
    Thanks in advance

    I wouldn't create three queries from the device itself. Create a separate service that does the three queries for you (could be as simple as a java webserver with a servlet) and reference that service in your java mobile application. Far easier to make secure also.
    And yeah to do three queries at once, you'd need multithreading I'd say. Or just execute the three consecutively, they shouldn't take much time anyway.

  • One of three conditions met, return true

    I just see the OR (Express Boolean) where if one of the TWO conditions met, then return true to stop the labview.
    Is there any Express Boolean provides if one of the THREE conditions met, return true?
    Solved!
    Go to Solution.

    compound arithmetic in the numerics . right click and change mode to or.  it is growable like an array.
    Paul Falkenstein
    Coleman Technologies Inc.
    CLA, CPI, AIA-Vision
    Labview 4.0- 2013, RT, Vision, FPGA

  • Need help with conditional query

    guys this is just an extension of this post that Frank was helping me with. im reposting because my requirements have changes slightly and im having a hell of a time trying to modify the query.
    here is the previous post.
    need help with query that can look data back please help.
    CREATE TABLE "FGL"
        "FGL_GRNT_CODE" VARCHAR2(60),
        "FGL_FUND_CODE" VARCHAR2(60),
        "FGL_ACCT_CODE" VARCHAR2(60),
        "FGL_ORGN_CODE" VARCHAR2(60),
        "FGL_PROG_CODE" VARCHAR2(60),
        "FGL_GRNT_YEAR" VARCHAR2(60),
        "FGL_PERIOD"    VARCHAR2(60),
        "FGL_BUDGET"    VARCHAR2(60)
      )data
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7600','4730','02','11','00','400');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7240','4730','02','10','1','100');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7240','4730','02','10','1','0');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7600','4730','02','11','1','400');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('360055','360055','7200','4730','02','10','1','400');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('360055','360055','7600','4730','02','10','1','400');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7240','4730','02','10','14','200');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7600','4730','02','10','14','100');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7240','4730','02','10','14','200');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7240','4730','02','10','2','100');
    Insert into FGL (FGL_GRNT_CODE,FGL_FUND_CODE,FGL_ACCT_CODE,FGL_ORGN_CODE,FGL_PROG_CODE,FGL_GRNT_YEAR,FGL_PERIOD,FGL_BUDGET) values ('240055','240055','7240','4730','02','11','2','600');
    I need to find the greatest grant year for the grant by a period parameter.
    once i find the greatest year i need to check the value of period 14 for that grant for the previous year and add it to the budget amount for that grant. however if their is an entry in the greatest year for period 00 then i need to ignore the period 14 of previous year and do this calculation current period +(current period - greatest year 00)
    hope that makes sense so in other words with the new data above. if i was querying period two of grant year 11. i would end up with $800
    because the greatest year is 11 it contains a period 0 with amount of $400 so my total should be
    period 2 amount $ 600
    period 0 amount $ 400 - period 2 amount of $600 = 200
    600+200 = $800
    if i query period 1 of grant 360055 i would just end up with 800 of grnt year 10.
    i have tried to modify that query you supplied to me with no luck. I have tried for several day but im embarrased to say i just can get it to do what im trying to do .
    can you please help me out.
    here is the query supplied by frank kulash who gracefully put this together for me.
    WITH     got_greatest_year     AS
         SELECT     fgl.*     -- or whatever columns are needed
         ,     MAX ( CASE
                     WHEN  fgl_period = :given_period
                     THEN  fgl_grnt_year
                    END
                  ) OVER ()     AS greatest_year
         FROM     fgl
    SELECT     SUM (fgl_budget)     AS total_budget     -- or SELECT *
    FROM     got_greatest_year
    WHERE     (     fgl_grnt_year     = greatest_year
         AND     fgl_period     = :given_period
    OR     (     fgl_grnt_year     = greatest_year - 1
         AND     fgl_period     = 14
    ;Miguel

    Hi, Miguel,
    Are you waying that, when the greatest year that has :given_period also has period='00' (or '0', or whatever you want to use), then you want to double the budget from the given_period (as well as subtract the budget from the '00', and not count the pevious year's '14')? If so, add another condition to the CASE statement which decides what you're SUMming:
    WITH     got_greatest_year     AS
         SELECT       TO_NUMBER (fgl_grnt_year)     AS grnt_year
         ,       fgl_period
         ,       TO_NUMBER (fgl_budget)     AS budget
         ,       MAX ( CASE
                       WHEN  fgl_period = :given_period
                       THEN  TO_NUMBER (fgl_grnt_year)
                      END
                    ) OVER ()     AS greatest_year
         FROM       fgl
    ,     got_cnt_00     AS
         SELECT     grnt_year
         ,     fgl_period
         ,     budget
         ,     greatest_year
         ,     COUNT ( CASE
                       WHEN  grnt_year     = greatest_year
                       AND       fgl_period     = '00'
                       THEN  1
                         END
                    ) OVER ()          AS cnt_00
         FROM    got_greatest_year
    SELECT       SUM ( CASE
                        WHEN  grnt_year     = greatest_year                    -- New
                  AND       fgl_period     = :given_period                    -- New
                  AND       cnt_00     > 0            THEN  budget * 2     -- New
                        WHEN  grnt_year     = greatest_year
                  AND       fgl_period     = :given_period       THEN  budget
                        WHEN  grnt_year     = greatest_year
                  AND       fgl_period     = '00'            THEN -budget
                        WHEN  grnt_year     = greatest_year - 1
                  AND       fgl_period     = '14'     
                  AND       cnt_00     = 0            THEN  budget
                    END
               )          AS total_budget
    FROM       got_cnt_00
    ;You'll notice this is the same as the previous query I posted, except for 3 lines maked "New".

  • I need to update a table with three conditions to check help me to solve this?

    GO
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    DROP PROCEDURE [dbo].[HRM_AssignInsuranceUpdate]
    GO
    CREATE PROCEDURE [dbo].[HRM_AssignInsuranceUpdate]
    @ID INT,
    @InsuranceTypeID BIGINT,
    @CompanyID BIGINT,
    @EmpID BIGINT,
    @InsuredObject NVARCHAR(250),
    @PolicyNumber NVARCHAR(250),
    @StartDate DATE,
    @ExpiryDate DATE,
    @Remarks NVARCHAR(MAX),
    @UpdatedBy NVARCHAR(150)
    AS
    BEGIN
    IF NOT EXISTS (SELECT * FROM dbo.HRMAssignInsurance WHERE InsuredObject = @InsuredObject
    AND InsuranceTypeID = @InsuranceTypeID AND CompanyID = @CompanyID AND IsActive = 1)
    BEGIN
    UPDATE HRMAssignInsurance
    SET InsuranceTypeID=@InsuranceTypeID,
    CompanyID=@CompanyID,
    EmployeeID=@EmpID,
    InsuredObject=@InsuredObject,
    PolicyNumber=@PolicyNumber,
    StartDate=@StartDate,
    ExpiryDate=@ExpiryDate,
    Remarks=@Remarks,
    UpdatedBy=@UpdatedBy
    WHERE ID = @ID
    SELECT @ID
    END
    ELSE
    BEGIN
    SELECT 0
    END
    END

    If you're using SQL Server 2008 and up, use MERGE command to incorporate your conditions into one command.
    Other wise change your query 
    to
    IF EXISTS (SELECT * FROM dbo.HRMAssignInsurance WHERE InsuredObject = @InsuredObject
    AND InsuranceTypeID = @InsuranceTypeID AND CompanyID = @CompanyID AND IsActive = 1)
    Thanks, 
    Shridhar J Joshi
    <If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'>

  • Help for conditional formatting of a chart query!!!!!

    Dear Gurus,
    can Anyone give me a step by step for conditional formatting on the chart?
    I want my charts in my queries to be for example:
    green color when actual data <= version,
    Yellow if actual > version & 101%, red if actual >=101%.
    Thank You very much for sharing your Knowledge.

    Hi Des,
    You can achieve this through exceptional reporting. Choose your query & execute the report. click on the 'Exceptions & Conditions' button. create the exception you wish to have by choosing version & your key figure, in your case. when you click 'Transfer' it automatically gets activated & you can be able to view the colors set by you.
    Revert back for any modifications.
    Manoj

  • Help with SQL Query Involving Three Database Tables

    Hi,
    My SQL is very rusty since I have not touched it in over one year.
    I was given an SQL question in a job interview and I am curious to know the right answer.
    This was a pre-prepared written test and the interviewer did not know the answer.
    There are three database tables: STUDENTS, COURSES and STUDENT_COURSES
    Table STUDENTS has STUDENT_ID and STUDENT_NAME columns.
    Table COURSES has COURSE_ID and COURSE_DESCRIPTION columns.
    Table STUDENT_COURSES has columns STUDENT_ID and COURSE_ID.
    Provide a query that returns all the students that are enrolled in all the courses.
    Thanks,
    Avi.

    It is probably good to say that this task may be solved such way, if database normalized and there are references
    Basically here just is a variant of your solution
    DROP TABLE student_course;
    DROP TABLE student;
    DROP TABLE course;
    CREATE TABLE student
    (student_id NUMBER(9) PRIMARY KEY,
    student_name VARCHAR2(30));
    CREATE TABLE course
    (course_id NUMBER(9) PRIMARY KEY,
    dscr VARCHAR2(100));
    CREATE TABLE student_course
    (student_id NUMBER(9),
    course_id NUMBER(9));
    ALTER TABLE student_course
    ADD CONSTRAINT pk_st_crs PRIMARY KEY
    (student_id, course_id);
    ALTER TABLE student_course
    ADD CONSTRAINT fk_student
      FOREIGN KEY (student_id)
      REFERENCES student(student_id);
    ALTER TABLE student_course
    ADD CONSTRAINT fk_course
      FOREIGN KEY (course_id)
      REFERENCES course(course_id);
    INSERT INTO student
         VALUES (1, 'NAME1');
    INSERT INTO student
         VALUES (2, 'NAME2');
    INSERT INTO student
         VALUES (3, 'NAME3');
    INSERT INTO course
         VALUES (101, 'Desc 1');
    INSERT INTO course
         VALUES (102, 'Desc 2');
    INSERT INTO course
         VALUES (103, 'Desc 3');
    INSERT INTO student_course
         VALUES (1, 101);
    INSERT INTO student_course
         VALUES (1, 102);
    INSERT INTO student_course
         VALUES (2, 101);
    INSERT INTO student_course
         VALUES (2, 103);
    INSERT INTO student_course
         VALUES (3, 101);
    INSERT INTO student_course
         VALUES (3, 102);
    INSERT INTO student_course
         VALUES (3, 103);
    COMMIT ;
    WITH st_crs_cnt AS
         (SELECT   student_id,
                   COUNT (*) tot
              FROM student_course
          GROUP BY student_id)
    SELECT sc.student_id,
           sc.tot
      FROM st_crs_cnt sc
      WHERE sc.tot = (SELECT COUNT (*) FROM course);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Where Condition Query Help

    I have a table with following data
    I need help in my where condition
    ID         Number   Token
    12100       V33     09
    12103       V66     03
    12103       V66     09
    12105       V77     09
    12106       V88     03
    12106       V88     09
    I want to put Token in Where condition like this
    If Token is only 3 for that ID then It will show following records
    ID         Number   Token
    12103       V66     03
    12106       V88     03
    If User asks for Token 09 record then It will exclusively show record  with 09 with not with 03 and with 09 records
    So Output will be like this
    ID         Number   Token
    12100        V33     09
    12105       V77     09

    hi,
    try this,
    select
    from tokenid
    where
    token = 09
    and
      number not
    in(select
    number  from tokenid
    where
    token = 03
    GVRSPK VENI

  • Query help for where condition

    Hi ,
    I have String value in table now I require to check that value is valid or not .
    I have below Query .
    SELECT *
    FROM Table TCI
    WHERE (ISDATE(SUBSTRING(SUBSTRING(Data,82,6),1,4)+'-'+SUBSTRING(SUBSTRING(Data,82,6),5,2)+'-'+'01')<>1 OR LEN(LTRIM(RTRIM(SUBSTRING(Data,82,6)))) < 0 OR SUBSTRING(Data,82,6)='000000')
    AND (LEN(LTRIM(RTRIM(SUBSTRING(Data,88,6)))) < 0 OR SUBSTRING(Data,88,6)= '000000' OR ISDATE(SUBSTRING(SUBSTRING(Data,88,6),1,4)+'-'+SUBSTRING(SUBSTRING(Data,88,6),5,2)+'-'+'01')<>1)
    AND (LEN(LTRIM(RTRIM(SUBSTRING(Data,173,6)))) < 0 OR ISDATE(SUBSTRING(SUBSTRING(Data,173,6),1,4)+'-'+SUBSTRING(SUBSTRING(Data,173,6),5,2)+'-'+'01')<>1)
    AND (LEN(LTRIM(RTRIM(SUBSTRING(Data,195,6)))) < 0 OR ISDATE(SUBSTRING(SUBSTRING(Data,195,6),1,4)+'-'+SUBSTRING(SUBSTRING(Data,195,6),5,2)+'-'+'01') <>1)
    AND (LEN(LTRIM(RTRIM(SUBSTRING(Data,217,7))))<0 OR ISNUMERIC(LTRIM(RTRIM(SUBSTRING(Data,217,7)))) <> 1)
    AND ISNUMERIC(REPLACE(SUBSTRING(Data,334,10),'-','0'))<>1
    AND ISNUMERIC(SUBSTRING(Data,345,10))<>1
    AND ISNUMERIC( SUBSTRING(Data,355,10))<>1
    AND ISNUMERIC(SUBSTRING(Data,416,8))<>1
    AND (LEN(LTRIM(RTRIM(SUBSTRING(Data,104,6))))<0 OR ISNUMERIC(SUBSTRING(Data,104,6))<>1)
    AND (LEN(LTRIM(RTRIM(SUBSTRING(Data,145,7))))<0 OR ISNUMERIC(SUBSTRING(Data,145,7))<>1)
    AND (LEN(LTRIM(RTRIM(SUBSTRING(Data,152,7))))<0 OR ISNUMERIC(SUBSTRING(Data,152,7))<>1)
    AND (LEN(LTRIM(RTRIM(SUBSTRING(Data,159,7))))<0 OR ISNUMERIC(SUBSTRING(Data,159,7))<>1)
    AND (LEN(LTRIM(RTRIM(SUBSTRING(Data,166,7))))<0 OR ISNUMERIC(SUBSTRING(Data,166,7))<>1)
    AND (LEN(LTRIM(RTRIM(SUBSTRING(Data,179,3))))<0 OR ISNUMERIC(SUBSTRING(Data,179,3))<>1)
    AND (LEN(LTRIM(RTRIM(SUBSTRING(Data,201,3))))<0 OR ISNUMERIC(SUBSTRING(Data,201,3))<>1)
    AND (ISNUMERIC(REPLACE(SUBSTRING(Data,365,10),'-','0'))<>1 OR ISNUMERIC( REPLACE(SUBSTRING(Data,365,10),'-','0'))<>1)
    AND (ISNUMERIC(REPLACE(SUBSTRING(Data,375,10),'-','0'))<>1 OR ISNUMERIC( REPLACE(SUBSTRING(Data,375,10),'-','0'))<>1)
    AND (ISNUMERIC(REPLACE(SUBSTRING(Data,385,10),'-','0'))<>1 OR ISNUMERIC(REPLACE(SUBSTRING(Data,385,10),'-','0'))<>1)
    AND (ISNUMERIC(REPLACE(SUBSTRING(Data,395,10),'-','0'))<>1 OR ISNUMERIC(REPLACE(SUBSTRING(Data,395,10),'-','0'))<>1)
    AND (ISNUMERIC(REPLACE(SUBSTRING(Data,405,10),'-','0'))<>1 OR ISNUMERIC(REPLACE(SUBSTRING(Data,405,10),'-','0'))<>1)
    I need only invalid record set from below Query ;
    like; If it is not isdate and is_numeric type for particular row then it return only that row.
    currently i'm facing issue like whole string is invalid in that case it gives row .
    should I use case statement in where clause ?
    Thanks
    Please Mark This As Answer or vote for Helpful Post if this helps you to solve your question/problem. http://techequation.com

    I need only invalid record set from below Query ;
    like; If it is not isdate and is_numeric type for particular row then it return only that row.
    currently i'm facing issue like whole string is invalid in that case it gives row .
    should I use case statement in where clause ?
    Hi PrajapatiNeha,
    Your requirement is confusing. Judging from the query, the column data
    seems to be a string which consists of fixed length date or numberic format substrings, so you are verifying each substring is valid and need to select the invalid substrings?
    If that is your requirement, why not just extract the substrings into a derived table and filter based on the derived table?  The substrings in the derived table will give a more directly overview of your long data string.
    If you have any question, feel free to let me know.
    Eric Zhang
    TechNet Community Support

Maybe you are looking for