SQL Query Help Needed

I'm having trouble with an SQL query. I've created a simple logon page wherein a user will enter their user name and password. The program will look in an Access database for the user name, sort it by Date/Time modified, and check to see if their password matches the most recent password. Unfortunately, the query returns no results. I'm absolutely certain that I'm doing the query correctly (I've imported it directly from my old VB6 code). Something simple is eluding me. Any help would be appreciated.
private void LogOn() {
//make sure that the user name/password is valid, then load the main menu
try {
//open the database connection
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:LawOffice2000", "", "");
Statement select = con.createStatement();
String strTemp = "Select * From EMPLOYEES Where INITIALS = '" + txtUserName.getText() + "' Order By DATE Desc, TIME Desc";
ResultSet result = select.executeQuery(strTemp);
while(result.next()) {
if (txtPassword.getPassword().toString() == result.getString("Password")) {
MenuMain.main();
else {
System.out.println("Password Bad");
System.out.println(txtUserName.getText());
System.out.println(result.getString("Password"));
break; //exit loop
//close the connection
con.close(); }
catch (Exception e) {
System.out.println("LawOfficeSuite_LogOn: " + e);
return; }
}

The problem is here: "txtPassword.getPassword().toString() == result.getString("Password"))"
Don't confuse String's equals() method with the equality operator '=='. The == operator checks that two references refer to the same object. If you want to compare the contents of Strings (whether two strings contain the same characters), use equals(), e.g. if (str1.equals(str2))...
Example:String s1 = "foo";
String s2 = new String("foo");
System.out.println("s1 == s2: " + (s1 == s2)); // false
System.out.println("s1.equals(s2): " + (s1.equals(s2))); // trueFor more information, check out Comparison operators: equals() versus ==

Similar Messages

  • Tweak for sql query - help needed for smalll change

    Hi.
    I am trying to run a script that checks for used space on all tablespaces and returns the results.
    So far so good:
    set lines 200 pages 2000
    col tablespace_name heading 'Tablespace' format a30 truncate
    col total_maxspace_mb heading 'MB|Max Size' format 9G999G999
    col total_allocspace_mb heading 'MB|Allocated' format 9G999G999
    col used_space_mb heading 'MB|Used' format 9G999G999D99
    col free_space_mb heading 'MB|Free Till Max' like used_space_mb
    col free_space_ext_mb heading 'MB|Free Till Ext' like used_space_mb
    col pct_used heading '%|Used' format 999D99
    col pct_free heading '%|Free' like pct_used
    break on report
    compute sum label 'Total Size:' of total_maxspace_mb total_allocspace_mb used_space_mb - free_space_mb (used_space_mb/total_maxspace_mb)*100 on report
    select
    alloc.tablespace_name,
    (alloc.total_allocspace_mb - free.free_space_mb) used_space_mb,
    free.free_space_mb free_space_ext_mb,
    ((alloc.total_allocspace_mb - free.free_space_mb)/alloc.total_maxspace_mb)*100 pct_used,
    ((free.free_space_mb+(alloc.total_maxspace_mb-alloc.total_allocspace_mb))/alloc.total_maxspace_mb)*100 pct_free
    FROM (SELECT tablespace_name,
    ROUND(SUM(CASE WHEN maxbytes = 0 THEN bytes ELSE maxbytes END)/1048576) total_maxspace_mb,
    ROUND(SUM(bytes)/1048576) total_allocspace_mb
    FROM dba_data_files
    WHERE file_id NOT IN (SELECT FILE# FROM v$recover_file)
    GROUP BY tablespace_name) alloc,
    (SELECT tablespace_name,
    SUM(bytes)/1048576 free_space_mb
    FROM dba_free_space
    WHERE file_id NOT IN (SELECT FILE# FROM v$recover_file)
    GROUP BY tablespace_name) free
    WHERE alloc.tablespace_name = free.tablespace_name (+)
    ORDER BY pct_used DESC
    The above returns something like this:
    MB MB % %
    Tablespace Used Free Till Ext Used Free
    APPS_TS_ARCHIVE 1,993.13 54.88 97.32 2.68
    APPS_TS_TX_IDX 14,756.13 1,086.88 91.37 8.63
    APPS_TS_TX_DATA 20,525.75 594.25 80.18 19.82
    APPS_TS_MEDIA 6,092.00 180.00 74.37 25.63
    APPS_TS_INTERFACE 13,177.63 366.38 71.49 28.51
    The above works fine, but I would like to further change the query so that only those tablespaces with free space less than 5% (or used space more than 95%) are returned.
    I have been working on this all morning and wanted to open it up to the masters!
    I have tried using WHERE pct_used > 95 but to no avail.
    Any advice would be appreciated.
    Many thanks.
    10.2.0.4
    Linux Red Hat 4.

    Thanks for that.
    What is confusing is that the below query works for every other (about 10 others) database but not this one (?)
    SQL> set lines 200 pages 2000
    SQL>
    SQL> col tablespace_name heading 'Tablespace' format a30 truncate
    SQL> col total_maxspace_mb heading 'MB|Max Size' format 9G999G999
    SQL> col total_allocspace_mb heading 'MB|Allocated' format 9G999G999
    SQL> col used_space_mb heading 'MB|Used' format 9G999G999D99
    SQL> col free_space_mb heading 'MB|Free Till Max' like used_space_mb
    SQL> col free_space_ext_mb heading 'MB|Free Till Ext' like used_space_mb
    SQL> col pct_used heading '%|Used' format 999D99
    SQL> col pct_free heading '%|Free' like pct_used
    SQL>
    SQL> break on report
    SQL> compute sum label 'Total Size:' of total_maxspace_mb total_allocspace_mb used_space_mb - free_space_mb (used_space_mb/total_maxspace_mb)*100 on report
    SQL>
    SQL> select /*+ALL_ROWS */
    2 alloc.tablespace_name,
    3 alloc.total_maxspace_mb,
    4 alloc.total_allocspace_mb,
    5 (alloc.total_allocspace_mb - free.free_space_mb) used_space_mb,
    6 free.free_space_mb+(alloc.total_maxspace_mb-alloc.total_allocspace_mb) free_space_mb,
    7 free.free_space_mb free_space_ext_mb,
    8 ((alloc.total_allocspace_mb - free.free_space_mb)/alloc.total_maxspace_mb)*100 pct_used,
    9 ((free.free_space_mb+(alloc.total_maxspace_mb-alloc.total_allocspace_mb))/alloc.total_maxspace_mb)*100 pct_free
    10 FROM (SELECT tablespace_name,
    11 ROUND(SUM(CASE WHEN maxbytes = 0 THEN bytes ELSE maxbytes END)/1048576) total_maxspace_mb,
    12 ROUND(SUM(bytes)/1048576) total_allocspace_mb
    13 FROM dba_data_files
    14 WHERE file_id NOT IN (SELECT FILE# FROM v$recover_file)
    15 GROUP BY tablespace_name) alloc,
    16 (SELECT tablespace_name,
    17 SUM(bytes)/1048576 free_space_mb
    18 FROM dba_free_space
    19 WHERE file_id NOT IN (SELECT FILE# FROM v$recover_file)
    20 GROUP BY tablespace_name) free
    21 WHERE alloc.tablespace_name = free.tablespace_name (+)
    22 ORDER BY pct_used DESC
    23 /
    ((alloc.total_allocspace_mb - free.free_space_mb)/alloc.total_maxspace_mb)*100 pct_used,
    ERROR at line 8:
    ORA-01476: divisor is equal to zero

  • SQL Server2008 help needed

    Having trouble with SQLServer 2008 (not MySQL) and my database connection in Dreamweaver CS6.  My document type is set as .asp using VBScript.  I can list the table information  but cannot use the insert wizard to add new records.  I don't get any errors after creating the insert form, but no records get inserted.  I'm not a VBScript expert, but do I have to manually write some code to insert records?  How do I attach it to a button?

    Thanks for the quick reply.  I won't be back in the office for a few days, but I'll try to post it when I get back in.  It's pretty much the code generated from the Dreamweaver Insert Record wizard.  I see where the submit button is created and the value is set but the action on the form is set to MM_insert, so I don't see where the submit code is actually called.
    Date: Wed, 3 Oct 2012 12:06:14 -0600
    From: [email protected]
    To: [email protected]
    Subject: SQL Server2008 help needed
        Re: SQL Server2008 help needed
        created by bregent in Dreamweaver General - View the full discussion
    This post should be moved to the app dev forum.  Please post the code from your form and the insert script pages.
         Please note that the Adobe Forums do not accept email attachments. If you want to embed a screen image in your message please visit the thread in the forum to embed the image at http://forums.adobe.com/message/4746757#4746757
         Replies to this message go to everyone subscribed to this thread, not directly to the person who posted the message. To post a reply, either reply to this email or visit the message page: http://forums.adobe.com/message/4746757#4746757
         To unsubscribe from this thread, please visit the message page at http://forums.adobe.com/message/4746757#4746757. In the Actions box on the right, click the Stop Email Notifications link.
         Start a new discussion in Dreamweaver General by email or at Adobe Community
      For more information about maintaining your forum email notifications please go to http://forums.adobe.com/message/2936746#2936746.

  • Query help needed

    Hi
    I need help in writing a sql query for the data given below
    Market Description Revenue
    LARGE CORPORATE 0.0
    LARGE CORPORATE 0.0
    OTHERS 0.0
    OTHERS 1.98
    LARGE CORPORATE 5.1299999999999999
    LARGE CORPORATE 6.8500000000000005
    LARGE CORPORATE 10.98
    LARGE CORPORATE 16.490000000000002
    LARGE CORPORATE 21.129999999999999
    LARGE CORPORATE 28.66
    LARGE CORPORATE 38.579999999999998
    OTHERS 68.420000000000002
    OTHERS 87.590000000000003
    LARGE CORPORATE 90.040000000000006
    LARGE CORPORATE 511.94
    LARGE CORPORATE 625.01999999999998
    LARGE CORPORATE 662.75999999999999
    LARGE CORPORATE 700.68000000000006
    LARGE CORPORATE 2898.6799999999998
    LARGE CORPORATE 3273.96
    OTHERS 3285.4400000000001
    LARGE CORPORATE 3580.0799999999999
    LARGE CORPORATE 4089.1900000000001
    LARGE CORPORATE 4373.5200000000004
    LARGE CORPORATE 16207.550000000001
    LARGE CORPORATE 19862.740000000002
    LARGE CORPORATE 33186.150000000001
    LARGE CORPORATE 107642.79000000001
    The output of query should be in the following format
    Market Description 1st 10%(revenue) 2nd 10%(revenue) 3rd 10%(revenue) 4th 10%(revenue) 5th 10%(revenue) rest 50%(revenue)
    Would appreciate any help on this query.

    Hi,
    What does 1st 10%, 2nd 10% etc. mean?
    Is it 0-10%, 11-20%, 21-30%....
    If so, combination of floor,decode and division should help to
    achieve the result.
    For example for the followint table,
    NAME SALE
    SALES_GROUP1 .2
    SALES_GROUP1 1
    SALES_GROUP1 9
    SALES_GROUP2 2.1
    SALES_GROUP2 12.2
    SALES_GROUP2 19.9
    SALES_GROUP3 22.2
    write,
    select name,decode(floor(sale/10),0,sale,null) "1st10%",
    decode(floor(sale/10),1,sale,null)"11to20%",
    decode(floor(sale/10),2,sale,null) "21to30%"
    from revenue;
    I mean, using floor and division, your rounding all values b/w 0 to 10 as 0
    Similarly, 11 to 20 has be rounded to 1 etc...then apply decode function it
    to achive the result.
    I hope this helps.
    Regards,
    Suresh
    8i OCP.

  • 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 Syntax - help needed

    Guys,
    Help me understand the syntax please!! With PL/SQL I have achieved a task quite easily, with a branch of code to include or exclude some part of the query - no problem. But to use SQL ......
    If i have a variable on a page, say :p10_open_or_closed
    .. and I set the value of this to the text "Is Not Null"
    How can I incorporate this into an SQL query, say
    Select ID, Date1, Date2, Comment
    From Table1
    where Date1 Is Not Null
    Is there a way of substituting the ":p10_open_or_closed" variable into this query?
    ie
    Select ID, Date1, Date2, Comment
    From Table1
    where Date1 ":p10_open_or_closed"
    Thanks.

    Thanks for your help gents.
    Originally, I had a PL/SQL Statement constructing the code as needed, as Rekha
    suggested.
    if :P1_OPEN_OR_CLOSED = 1 then
    q:=q||' and ';
    q:=q||' p.ACTUAL_INSTALL_DATE is null ';
    end if;
    if :P1_OPEN_OR_CLOSED = 2 then
    q:=q||' and ';
    q:=q||' p.ACTUAL_INSTALL_DATE is not null ';
    end if;
    But, to use a Tabular form, where users can update fields of multiple records on screen then submit for a MRU, the option of PL/SQL code is not allowed, only SQL. So Phil UK, no it's not an elegant way of doing things, but I'm forced to use SQL, yeah?
    There are definitely ways that I can filter for the solution I am after, but they all involve more in depth solutions (that are not that great). Thus, I asked at this forum.
    Andy, your solution works :~) which makes me very happy. I'm not sure how just now but I'll learn from it.
    Thanks again.

  • SQL Query Performance needed.

    Hi All,
       I am getting performance issue with my below sql query. When I fired it, It is taking 823.438 seconds, but when I ran query in, it is taking 8.578 seconds, and query after in   is taking 7.579 seconds.
    SELECT BAL.L_ID, BAL.L_TYPE, BAL.L_NAME, BAL.NATURAL_ACCOUNT,
     BAL.LOCATION, BAL.PRODUCT, BAL.INTERCOMPANY, BAL.FUTURE1, BAL.FUTURE2, BAL.CURRENCY, BAL.AMOUNT_PTD, BAL.AMOUNT_YTD, BAL.CREATION_DATE,
     BAL.CREATED_BY, BAL.LAST_UPDATE_DATE, BAL.LAST_UPDATED_BY, BAL.STATUS, BAL.ANET_STATUS, BAL.COG_STATUS, BAL.comb_id, BAL.MESSAGE,
     SEG.SEGMENT_DESCRIPTION  FROM ACC_SEGMENTS_V_TST SEG , ACC_BALANCE_STG BAL where BAL.NATURAL_ACCOUNT = SEG.SEGMENT_VALUE AND SEG.SEGMENT_COLUMN = 'SEGMENT99' AND BAL.ACCOUNTING_PERIOD = 'MAY-10' and BAL.comb_id
    in  
    (select comb_id from
     (select comb_id, rownum r from
      (select distinct(comb_id),LAST_UPDATE_DATE from ACC_BALANCE_STG where accounting_period='MAY-10' order by LAST_UPDATE_DATE )    
         where rownum <=100)  where r >0)
    Please help me in fine tuning above. I am using Oracle 10g database. There are total of 8000 records. Let me know if any other info required.
    Thanks in advance.

    In recent versions of Oracle an EXISTS predicate should produce the same execution plan as the corresponding IN clause.
    Follow the advice in the tuning threads as suggested by SomeoneElse.
    It looks to me like you could avoid the double pass on ACC_BALANCE_STG by using an analytical function like ROW_NUMBER() and then joining to ACC_SEGMENTS_V_TST SEG, maybe using subquery refactoring to make it look nicer.
    e.g. something like (untested)
    WITH subq_bal as
        ((SELECT *
          FROM (SELECT BAL.L_ID, BAL.L_TYPE, BAL.L_NAME, BAL.NATURAL_ACCOUNT,
                 BAL.LOCATION, BAL.PRODUCT, BAL.INTERCOMPANY, BAL.FUTURE1, BAL.FUTURE2,
                 BAL.CURRENCY, BAL.AMOUNT_PTD, BAL.AMOUNT_YTD, BAL.CREATION_DATE,
                 BAL.CREATED_BY, BAL.LAST_UPDATE_DATE, BAL.LAST_UPDATED_BY, BAL.STATUS, BAL.ANET_STATUS,
                 BAL.COG_STATUS, BAL.comb_id, BAL.MESSAGE,
                 ROW_NUMBER() OVER (ORDER BY LAST_UPDATE_DATE) rn
                 FROM   acc_balance_stg
                 WHERE  accounting_period='MAY-10')
          WHERE rn <= 100)
    SELECT *
    FROM   subq_bal bal
    ,      acc_Segments_v_tst seg
    where  BAL.NATURAL_ACCOUNT = SEG.SEGMENT_VALUE
    AND    SEG.SEGMENT_COLUMN = 'SEGMENT99';However, the parentheses you use around comb_id make me question what your intention is here in the subquery?
    Do you have multiple rows in ACC_BALANCE_STG for the same comb_id and last_update_date?
    If so you may want to do a MAX on last_update_date, group by comb_id before doing the analytic restriction.
    Edited by: DomBrooks on Jun 16, 2010 5:56 PM

  • What SQL query I need for this?

    I need to execute a SQL query but I don't know how.
    To illustrate it, please take a look at some example data:
        ARTICLEID SOLDON    
        1         2005-12-31
        1         2005-11-31
        1         2005-10-31
        1         2005-09-31
        1         2005-08-31
        1         2005-07-31
        1         2005-06-31
        1         2005-05-31
        1         2005-04-31
        1         2005-03-31
        1         2005-02-31
        1         2005-01-31
        1         2004-12-31
        1         2004-11-31
        2         2005-12-31
        2         2005-11-31
        2         2005-10-31
        2         2005-09-31 This is a piece of the sales data for the articles (sales history).
    Lets assume that today is the date 2005-12-31.
    Two requirements for the query:
    1. Get the sales data for the last 12 months.
    2. Get only the sales data for articles where there is sales data since at least 6 months.
    The result in my example should look like this:
        ARTICLEID SOLDON    
        1         2005-12-31
        1         2005-11-31
        1         2005-10-31
        1         2005-09-31
        1         2005-08-31
        1         2005-07-31
        1         2005-06-31
        1         2005-05-31
        1         2005-04-31
        1         2005-03-31
        1         2005-02-31
        1         2005-01-31 What is the SQL which I need to accomplish this query?

    To get all the information from the last 12 months
    you will have to use date manipulation.
    SELECT add_months(sysdate, -12) from
    dual;This gives you the date 12 months ago.
    So you will have to select your date between then and
    the current date.If I do this I will get this data:
        ARTICLEID SOLDON    
        1         2005-12-31
        1         2005-11-31
        1         2005-10-31
        1         2005-09-31
        1         2005-08-31
        1         2005-07-31
        1         2005-06-31
        1         2005-05-31
        1         2005-04-31
        1         2005-03-31
        1         2005-02-31
        1         2005-01-31
        2         2005-12-31
        2         2005-11-31
        2         2005-10-31
        2         2005-09-31 But I want this data:
        ARTICLEID SOLDON    
        1         2005-12-31
        1         2005-11-31
        1         2005-10-31
        1         2005-09-31
        1         2005-08-31
        1         2005-07-31
        1         2005-06-31
        1         2005-05-31
        1         2005-04-31
        1         2005-03-31
        1         2005-02-31
        1         2005-01-31 I am no native English speaker. What didn't you understand in the two requirements?
    Here are my two requirements for the query:
    1. Get the sales data for the last 12 months.
    2. But get ONLY the sales data for articles where there is sales data since AT LEAST 6 months.
    The result can contain as many IDs as you want if the two requirements are met. Its not a trivial SQL statement for me. Please remember that the above data are only for illustration. They are just an example.
    There should be a SQL statement for this.
    Please tell me if you don't understand my problem. I will try to explain it in a better way if I can.

  • Sql query ..need idea to write complex query

    Hi there,
    I have assigned the task to write a sql query to get the output as the below stored proc does.
    In the proc conditions are given with IF statements. I really dont know how to give all the conditions for the period in a single sql query as I'm not much used to sql quries.
    Is anyone could help me?
    Any suggestions pls . writing complicated query is nightmare. no idea . if possible help me...
    create or replace PROCEDURE vpp_station_summary_report (
    in_user_id                     IN  VARCHAR2,
    in_report_id      IN  NUMBER,
    in_time_from                IN      vppstation.avi_status_history.status_eff_date%TYPE,
    in_time_to                  IN  vppstation.avi_status_history.status_eff_date%TYPE,
    result                               OUT SYS_REFCURSOR)
    AS
    CURSOR station_loop IS
       SELECT ash.station_id,
              ash.avi_id,
              ash.state_id,
              ash.state_eff_date
       FROM   vppstation.avi_state_history ash
       JOIN   vpproadside.vpp_report_stations
         ON   vpp_report_stations.station_id             = ash.station_id
        AND   vpp_report_stations.vpp_report_seq_number  = in_report_id
       WHERE  ash.state_eff_date BETWEEN in_time_from AND in_time_to
       ORDER BY ash.station_id,
                ash.avi_id,
                ash.state_eff_date,
                ash.ash_id;
    -- cursor to find the 'entry state' i.e. the state the AVI was in AT the time of
    -- in_time_from
    CURSOR entry_state (
              state_station_id vppstation.avi_state_history.station_id%TYPE,
              state_avi_id     vppstation.avi_state_history.avi_id%TYPE,
              state_state_date vppstation.avi_state_history.state_eff_date%TYPE
    IS
       SELECT ash.state_id
       FROM   vppstation.avi_state_history ash
       WHERE  ash.station_id = state_station_id
         AND  ash.avi_id = state_avi_id
         AND  ash.state_eff_date < state_state_date
       ORDER BY ash.state_eff_date DESC,
                ash.ash_id DESC;
    current_station_id         vppstation.avi_state_history.station_id%TYPE;
    current_avi_id             vppstation.avi_state_history.avi_id%TYPE;
    current_state_id           vppstation.avi_state_history.state_id%TYPE;
    current_state_eff_date     vppstation.avi_state_history.state_eff_date%TYPE;
    period_length NUMBER;
    next_station_id     vppstation.avi_state_history.station_id%TYPE;
    next_avi_id         vppstation.avi_state_history.avi_id%TYPE;
    next_state_id       vppstation.avi_state_history.state_id%TYPE;
    next_state_eff_date vppstation.avi_state_history.state_eff_date%TYPE;
    station_open_total       NUMBER;
    station_closed_total     NUMBER;
    station_all_report_total NUMBER;
    current_station_name vpproadside.vpp_station_summary.station_name%TYPE;
    state_open       vppstation.avi_control_state_code.state_id%TYPE;
    state_closed     vppstation.avi_control_state_code.state_id%TYPE;
    state_all_report vppstation.avi_control_state_code.state_id%TYPE;
    BEGIN
    SELECT state_id
    INTO   state_open
    FROM   vppstation.avi_control_state_code
    WHERE  state_type = 'E'
    AND    state_active_ind = 'A';
    SELECT state_id
    INTO   state_closed
    FROM   vppstation.avi_control_state_code
    WHERE  state_type = 'D'
    AND    state_active_ind = 'A';
    SELECT state_id
    INTO   state_all_report
    FROM   vppstation.avi_control_state_code
    WHERE  state_type = 'S'
    AND    state_active_ind = 'A';
    current_station_id := -1;
    current_avi_id     := -1;
    current_state_id   := state_closed;
    current_state_eff_date := in_time_from;
    station_open_total       := 0.0;
    station_closed_total     := 0.0;
    station_all_report_total := 0.0;
    -- for starters - ensure that there is report data for all requested stations...
    INSERT INTO vpproadside.vpp_station_summary
          vpp_report_seq_number,
          station_id,
          station_name,
          ln_number,
          lane_name,
          station_open,
          station_close,
          station_all_report,
          station_total
      SELECT in_report_id,
             vrs.station_id,
             si.station_name,
             l.ln_number,
             l.lane_name,
             0.0,
             0.0,
             0.0,
             0.0
      FROM vpproadside.vpp_report_stations vrs
      LEFT OUTER JOIN  vpproadside.stations_installed si
        ON  si.station_id = vrs.station_id
      LEFT OUTER JOIN vppstation.lane_name l
        ON l.station_id = vrs.station_id
      WHERE vrs.vpp_report_seq_number  = in_report_id;
    -- loop over state history and update information for all stations found
    OPEN station_loop;
    LOOP
      FETCH station_loop
      INTO
            next_station_id,
            next_avi_id,
            next_state_id,
            next_state_eff_date;
      IF station_loop%NOTFOUND THEN
        next_station_id := -1;
        next_avi_id     := -1;
      END IF;
      -- if station/avi has changed take the end of the report period
      IF    (next_station_id <> current_station_id)
         OR (next_avi_id     <> current_avi_id)
      THEN
        period_length := in_time_to - current_state_eff_date;
      ELSE
        -- otherwise the start of the next period marks the end of the current period
        period_length := next_state_eff_date - current_state_eff_date;
      END IF;
      -- if we have a real station id then do some work...
      IF (current_station_id <> -1) THEN
        -- determine which category the period fits to and apply calculation
        IF current_state_id = state_open THEN
          station_open_total := station_open_total + period_length - 1;
        ELSIF current_state_id = state_closed THEN
          station_closed_total := station_closed_total + period_length - 1;
        ELSIF current_state_id = state_all_report THEN
          station_all_report_total := station_all_report_total + period_length - 1;
        ELSE
          RAISE_APPLICATION_ERROR(-20111, 'Error: found unknown state code on avi_state_history - ' || current_state_id );
        END IF;
        -- if the station/avi has changed then commit changes to db
        IF    (next_station_id <> current_station_id)
           OR (next_avi_id     <> current_avi_id)
        THEN
          UPDATE vpproadside.vpp_station_summary
          SET
              station_open       = station_open_total,
              station_close      = station_closed_total,
              station_all_report = station_all_report_total
          WHERE vpp_report_seq_number = in_report_id
          AND   station_id = current_station_id
          AND   ln_number  = current_avi_id;
          -- reset counts
          station_open_total       := 0.0;
          station_closed_total     := 0.0;
          station_all_report_total := 0.0;
        END IF;
      END IF;
      -- if we got past the last record then stop processing
      EXIT WHEN station_loop%NOTFOUND;
      -- if the station/avi is changing, get the state that was 'current' at in_time_from
      IF    (next_station_id <> current_station_id)
         OR (next_avi_id     <> current_avi_id)
      THEN
        current_state_eff_date := in_time_from;
        OPEN entry_state (
               next_station_id,
               next_avi_id,
               in_time_from
        FETCH entry_state
        INTO  current_state_id;
        IF entry_state%NOTFOUND THEN
          current_state_id := state_closed;
        END IF;
        CLOSE entry_state;
        period_length := next_state_eff_date - current_state_eff_date;
        IF current_state_id = state_open THEN
          station_open_total := station_open_total + period_length;
        ELSIF current_state_id = state_closed THEN
          station_closed_total := station_closed_total + period_length;
        ELSIF current_state_id = state_all_report THEN
          station_all_report_total := station_all_report_total + period_length;
        ELSE
            RAISE_APPLICATION_ERROR(-20111, 'Error: found unknown state code on avi_state_history - ' || current_state_id );
        END IF;
      END IF;
      current_state_id       := next_state_id;
      current_state_eff_date := next_state_eff_date;
      current_station_id     := next_station_id;
      current_avi_id         := next_avi_id;
    END LOOP;
    CLOSE station_loop;
    -- update the totals for the percentage calculation
    UPDATE vpproadside.vpp_station_summary
    SET
           station_total = station_open + station_close+ station_all_report
    WHERE   vpp_report_seq_number = in_report_id;
    -- 'fix' the totals that are still zero to avoid divide by zero errors...
    --       note: all the percentages will still come out as zero since the total
    --             was zero
    UPDATE vpproadside.vpp_station_summary
    SET
           station_total = 1.0
    WHERE  vpp_report_seq_number = in_report_id
    AND    station_total = 0.0;
    OPEN result FOR
    SELECT station_name "Site Name",
           lane_name    "Lane Name",
           TO_CHAR((station_open       / station_total) * 100.0, 'FM990.0999') || '%' "Open %",
           TO_CHAR((station_close      / station_total) * 100.0, 'FM990.0999') || '%' "Closed %",
           TO_CHAR((station_all_report / station_total) * 100.0, 'FM990.0999') || '%' "All Report %"
    FROM vpproadside.vpp_station_summary
    WHERE vpp_report_seq_number = in_report_id
    ORDER BY UPPER(station_name),
             UPPER(lane_name);
    DELETE FROM vpproadside.vpp_station_summary
    WHERE vpp_report_seq_number = in_report_id;
    END;Edited by: Indhu Ram on Mar 10, 2010 9:51 AM
    Edited by: Indhu Ram on Mar 10, 2010 9:56 AM
    Edited by: Indhu Ram on Mar 10, 2010 10:58 AM
    Edited by: Indhu Ram on Mar 10, 2010 11:12 AM

    Exactly dont know what you are asking for but I can suggest you some tips here
    - If you want to check the condition in SQL query then you can use CASE statement into select clause i.e.
    SELECT CASE when table1.a=table2.b then table1.c else table2.c END, ... more case..., table columns...
    FROM table1, table2
    WHERE
    <some conditions>
    - If you want to achive same functionality (SELECT only, not UPDATE/INSERT/DELETE) then you can convert the part of same procedure into function and can use the same function into your query by passing the parameters.
    something like this
    SELECT function_name(parameter1, parameter2....) from dual
    Hope this will help

  • Simpler reprsentation to SQL Query is needed

    Hi all,
    I have this SQL Query working goon on the Database but have some errors with Form developer so can anybody simplify it?
         SELECT *
                 FROM (SELECT   COUNT (returned_goods.ID) AS "Max Occurence", products.Name
                           FROM Returned_Goods
                           JOIN Products
                           ON returned_goods.productId = products.Id
                           GROUP BY returned_goods.productId, products.Name
                           ORDER BY COUNT (returned_goods.ID) DESC)
            WHERE ROWNUM = 1;btw, the error encounter me in Forms appears here if anybody can help: [SQL Code not working in Forms Developer without Functions|http://forums.oracle.com/forums/thread.jspa?threadID=842122&tstart=0]
    Thanks in advance :)

    The simpler SQL Staement is
    SELECT *
      FROM (SELECT   COUNT (returned_goods.ID) AS "Max Occurence", products.Name
      FROM returned_goods, products
         WHERE
         Returned_Goods.ProductId = Products.id
             GROUP BY returned_goods.productId, products.Name
             ORDER BY COUNT (returned_goods.ID) DESC)
    WHERE ROWNUM = 1;

  • Sql query - help reqd

    Hi,
    I require help for sql query. The query will be like
    "SELECT * FROM XYZ WHERE TEXT = 'h*s' "
    and the results will be come like
    “his”
    “homes”
    “houses”
    “horses”,
    “horticulturalists”
    “herbaceous”.
    Thanks,
    Kapil

    Hello,
    SELECT   *
      FROM   XYZ
    WHERE   TEXT LIKE ('h%s');Regards
    Edited by: OrionNet on Feb 2, 2009 12:33 AM

  • Sql query - help reqd (new)

    Hi,
    I have follwing dataset
    "herb with garden"
    "garden without herb"
    "herb with zbc"
    "garden with pqr"
    Now i want sql query like
    select * from table where text1 = "herb and garden"
    This should populate
    herb with garden
    garden without herb
    And
    select * from table where text1 = "herb or garden"
    This should populate
    "herb with garden"
    "garden without herb"
    "herb with zbc"
    "garden with pqr"

    SQL> with t
      2  as
      3  (
      4     select 'herb with garden' str from dual union all
      5     select 'garden without herb' str from dual union all
      6     select 'herb with zbc' str from dual union all
      7     select 'garden with pqr' str from dual
      8  )
      9  select *
    10    from t
    11   where lower(str) like '%herb%'
    12     and lower(str) like '%garden%'
    13  /
    STR
    herb with garden
    garden without herb
    SQL> with t
      2  as
      3  (
      4     select 'herb with garden' str from dual union all
      5     select 'garden without herb' str from dual union all
      6     select 'herb with zbc' str from dual union all
      7     select 'garden with pqr' str from dual
      8  )
      9  select *
    10    from t
    11   where lower(str) like '%herb%'
    12     or lower(str) like '%garden%'
    13  /
    STR
    herb with garden
    garden without herb
    herb with zbc
    garden with pqr

  • UCCX SQL query assistance needed.

    Hello,
    I am working on a SQL query that does a lookup of the calling number and the last four digits entered by the customer.  If I hard code the lastFourGC variable I am able to return a successful result.  If I use $lastFourGC I get the following error.
    $callingNumber  - Is exactly that, the calling number.
    $lastFourGC - Is the last four digits collected from the customer.
    SELECT * FROM GiftCardFulfillment WHERE Phone=$callingNumber and Right (GiftCard16DigitNumber, 4)=$lastFourGC

    Tanner,
    I had tried that with single and double quotes and it didn't work.  I did end up getting it to work by rearranging the order.  I'm not sure why that worked, but this is what the query looks like now and it works.
    SELECT * FROM [leads].[dbo].[GiftCardFulfillment]   
             WHERE Right (GiftCard16DigitNumber, 4)=$lastFourGC and Phone=$callingNumber

  • SOLVED - Query help needed

    i want an sql query such that it can fetch elements which have only one entry in the table.
    For instance, say the table contains a record of the people who have borrowed books from a library.
    Name ---- Book ---- Date
    AA -------- B1 --------- xx
    AA -------- B2 --------- xx
    BB -------- B3 --------- xx
    CC -------- B4 --------- xx
    So i want to be able to fetch all names which have just one record in the table, using a query.
    And if its possible to also be able to fetch records which have a required number of records in the table, or is it too much to ask in a query!
    Message was edited by:
    user648852

    Hi,
    That's no problem using GROUP BY and HAVING:
    SELECT    name
    FROM      borrowed_books
    GROUP BY  name
    HAVING    COUNT (*) = 1   -- or any number you want
    ;

  • Need SQL Query Help

    I need help combining two queries into one. This is what I
    have now:
    <CFQUERY NAME="getInfo" datasource="myDS"
    BLOCKFACTOR="100">
    SELECT
    status.status_doc_id,
    status.date_accepted,
    status.date_received,
    document_main.document_main_doc_type,
    document_main.document_main_doc_id,
    document_main_account_id,
    document_main_company_account_id,
    document_main_period_of_report,
    users_account.client_name,
    users_account.account_type
    FROM
    status,
    document_main, users_account
    WHERE
    status.filing_status_user_id = '2'
    AND status.Statustype = 'Live'
    AND status.Currentstatus = 'Accepted'
    AND status.status_doc_id =
    document_main.document_main_doc_id
    AND users_account.account_id =
    document_main.document_main_company_account_id
    </CFQUERY>
    <CFQUERY NAME="getStuff" datasource="myDS"
    BLOCKFACTOR="100">
    SELECT
    users_account.client_name,
    FROM
    users_account
    WHERE
    account_id = '#getInfo.document_main_account_id#'
    AND account_type = 'Individual'
    </CFQUERY>
    The problem is that the account_id referred to in the
    users_account table can be either a Company or an Individual. So in
    my html table the output would list both. A co-worker suggested a
    UNION ALL and to alias the client_name fields. But that query seems
    to ignore the alias after the union.
    Can anyone help me out?

    Thanks for your help Dan.
    I added this to the query:
    CASE users_account.account_type
    WHEN 'Company' THEN users_account.client_name
    END AS COMPANYNAME,
    CASE users_account.account_type
    WHEN 'Individual' THEN users_account.client_name
    END AS IndiNAME
    The problem I have is that because of:
    AND users_account.account_id =
    document_main.document_main_company_account_id
    the output is empty for "IndiNAME".
    Users_account.account_id can refer to a record
    with"individual" or "company" as the account type. So in the same
    record in document_main, document_main_account_id refers back to an
    individual while document_main_company_account_id refers back to a
    company account.
    So of course if I change the above to:
    AND users_account.account_id =
    document_main.document_main_account_id
    then "COMPANYNAME" is empty in the output.
    I can't figure out how to get those two values without one or
    the other being empty (or breaking the link altogether from the
    document_main table to the users_account table).

Maybe you are looking for

  • HT4314 Game center will not recognize that I play any game center games.

    Game center will not recognize that I play any game center games. Also, my friends can interact with my game saves, but I cannot, because they do not appear in the "friends/neighbors" window when I play. What can I do to fix this?

  • My photoshop is not linking with the creative cloud

    I am logged into the Creative Cloud but when I  run my Photoshop program it tells me I need to log into the creative cloud to access my library.

  • HT1766 i tried to update phone now its wont turn on

    I updated my phone as requested by itunes and now it won't turn on and asks me to restore to original settings.  The photo is itunes with a cord

  • VPN between IOS and ASA

    Hello my friends, I have been trying to establish VPN connectivity between IOS cisco router and ASA firewall over the internet - no luck so far. I think I am missing some important bit of the configuration. Here are my configuration commands: Router:

  • SystemTray & Dockable window

    Dear Friends, 1) i have created an air application (Ticker) please tel me how can i create the dockable screen. my ticker screen is dragging fine. if i drag the ticker screen near the top of the desktop screen, it should go and stick on the top of th