Learning SQL Query with JCheckBox and JButton

Hello,
I am learning how to access a very simple Access table. I am able to connect to the database and return a simple query. As I make it more complicated is where I have confused myself. The program is suppose to allow the user to pick any field they want to query using JCheckBox. After they have checked the fields off, the run query button is hit and outputs the results in a JOPtion Pane with a JTable. I am trying to do a test run and I can't make the query at least output something. If I can get any clues to the right direction would be appreciated. Thanks.
package mypackage25;
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class QueryAddressBook extends JFrame
    private JLabel selectQueryLabel;
    private JCheckBox firstName, lastName,
                   telephone, addressI, addressII, city,
                   state, zip;
    private JPanel selectQueryPanel, checkBoxPanel, executePanel;
    private JButton runQueryButton, clearSQLButton;
    private Connection connection;
    private Statement statement;
    private ResultSet resultSet;
    public QueryAddressBook()
      super("Query an Address Book");
      //Driver and Connection
      try
      //Driver for MicrosoftAccess
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      //Inform the user that the Driver was loaded successfully
      System.out.println("Driver Loaded");
      //Connect to specific database(i.e. MyAddress3) in Access
      Connection connection=DriverManager.getConnection("jdbc:odbc:MyAddress3");
      //Inform User
      System.out.println("Database connected");
      }//end try
      catch(ClassNotFoundException cnfe)
        cnfe.printStackTrace();
      }//end catch
      catch(SQLException sqle)
        sqle.printStackTrace();
      }//end catch
      //get content pane and set its layout
      Container container=getContentPane();
      container.setLayout(new BorderLayout());
      //GUI Components
      selectQueryLabel=new JLabel("Select Fields to be Queried");
      firstName=new JCheckBox("First Name");
      lastName=new JCheckBox("Last Name");
      telephone=new JCheckBox("Telephone");
      addressI=new JCheckBox("Address I");
      addressII=new JCheckBox("Address II");
      city=new JCheckBox("City");
      state=new JCheckBox("State");
      zip=new JCheckBox("Zipcode");
      //register listeners for JCheckBoxes
      CheckBoxHandler handler=new CheckBoxHandler();
      firstName.addItemListener(handler);
      lastName.addItemListener(handler);
      telephone.addItemListener(handler);
      addressI.addItemListener(handler);
      addressII.addItemListener(handler);
      city.addItemListener(handler);
      state.addItemListener(handler);
      zip.addItemListener(handler);
      //set up selectQueryPanel
      selectQueryPanel=new JPanel();
      selectQueryPanel.setLayout(new FlowLayout());
      selectQueryPanel.add(selectQueryLabel);
      //set up CheckBox Panel
      checkBoxPanel=new JPanel();
      checkBoxPanel.setLayout(new FlowLayout());
      checkBoxPanel.add(firstName);
      checkBoxPanel.add(lastName);
      checkBoxPanel.add(telephone);
      checkBoxPanel.add(addressI);
      checkBoxPanel.add(addressII);
      checkBoxPanel.add(city);
      checkBoxPanel.add(state);
      checkBoxPanel.add(zip);
      //set up execute panel
      executePanel=new JPanel();
      executePanel.setLayout(new FlowLayout());
      //set up buttons
      runQueryButton=new JButton("Run Query");
      clearSQLButton=new JButton("Clear SQL");
      runQueryButton.addActionListener
        new ActionListener()
          public void actionPerformed(ActionEvent event)
            if(event.getSource().equals(runQueryButton))
              runSQLQuery();
      executePanel.add(runQueryButton);
      executePanel.add(clearSQLButton);
      container.add(selectQueryPanel, BorderLayout.NORTH);
      container.add(checkBoxPanel, BorderLayout.CENTER);
      container.add(executePanel, BorderLayout.SOUTH);
      setSize(800,150);
      setVisible(true);
    public static void main(String args[])
      QueryAddressBook dwgui=new QueryAddressBook();
      dwgui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }//end main
    //private inner class for ItemListener event handling
    private class CheckBoxHandler implements ItemListener
      public void itemStateChanged(ItemEvent event)
      }//end method itemStateChanged
    }//end private inner class CheckBoxHandler
    private void runSQLQuery()
      String output="";
      try
        statement=connection.createStatement();
        resultSet=statement.executeQuery("select firstName from address");
        while(resultSet.next())
          output+=resultSet.getString(1)+"\n";
        JOptionPane.showMessageDialog(null,output);
        System.out.println(output);
      }//end try
      catch(SQLException sqle)
        sqle.printStackTrace();
      }//end catch
    }//end runSQLQuery
}//end class

At present your query string is
"Select firstName from Address"
Instead of using the above hardcoded string, try to build the
query String using logic that checks which check boxes are selected
by the user.
Example..
String query = "SELECT ";
if (firstName.isSelected()) {
query = query + " firstName";
Be sure, you add the comma properly between two fields :-)

Similar Messages

  • SQL query with JSP and WML-parameters

    Hey,
    Could you help me?
    I'm trying to do the following. WML deck card 1 send parameter to same WML deck's card help. I try to read the parameter with JSP in card help by putting the parameter to SQL query, but it doesn't work. I can read the parameter with WML in card help. I can also print the value of the parameter with JSP if I generate WML with JSP.
    /*parameter sending from card 1 to card help*/
    out.println("<go href='#helpcard'>");
    out.println("<setvar name='valittukurssi' value='$(valittukurssi)'/>");
    /*parameter read with WML in card help */
    <p>Valitse kurssi.
    $valittukurssi</p>
    /'parameter read with JSP by generating WML with JSP*/
    out.println("<p>$valittukurssi</p>");
    /* SQL query with JSP */
    ResultSet uudettulokset = uusilause.executeQuery("select * from kurssi where lyhenne='$valittukurssi'");
    Thanks,
    Rampe

    You're problem is easy to fix. You're confusing WML variables with JSP variables. See below:
    >
    /*parameter sending from card 1 to card help*/
    out.println("<go href='#helpcard'>");
    out.println("<setvar name='valittukurssi'
    value='$(valittukurssi)'/>");
    Above you set a var that will work on the phone, not in JSP.
    /*parameter read with WML in card help */
    <p>Valitse kurssi.
    $valittukurssi</p>
    Yes the above does display the parameter, because it is a client side WML var, but you cannot use this variable in the JSP code (that's why your SWL fails).
    /'parameter read with JSP by generating WML with
    JSP*/
    out.println("<p>$valittukurssi</p>");Here's you're problem, the above line is EXACTLY the same as the one before it. When the container parses through this JSP code it translates the above line to:
    <p>$valittukurssi</p> on the WML page and the CLIENT uses it's local variable to display it.
    What you need and want is to have a variable that can be used in JSP code and output to your WML page. Here's how it's done:
    out.println("<go href='#helpcard'>");
    String some_name = "valittukurssi";
    out.println("<setvar name='"+some_name+"'
    value='$("+some_name+")'/>");
    //note that you may have to escape the ( and ) with a \
    //so we displayed the variable above into the WML page, now we can use it in the SQL query:
    /* SQL query with JSP */
    ResultSet uudettulokset =
    uusilause.executeQuery("select * from kurssi where
    lyhenne='"+some_name+"'");//the end of the command is: " ' " ) ;
    Frank Krul
    Got Node?

  • Sql query with conditions and calculations???

    Hi,
    how I can build a query with conditions and calculations?
    E.g. I've got this table
    Start          | End     |     Working Place     |     Mandatory
    01-JAN-13 | 11-JAN-13 |     Office           |          1
    14-JAN-13 | 25-JAN-13 |     Home Office      |     0
    04-MRZ-13| 15-MRZ-13 |     Office           |          0
    11-FEB-13 | 22-FEB-13 |     Office           |          1
    Now if column working place=Office and column mandatory=0
    the new column "price" has to calculate: (End-Start)* $25.00
    and if working place=Office and column mandatory=1
    the "price" column has to calculate: (End-Start)* $20.60
    else $0.00
    I tried it with the case statement but I didn't know how
    to calculate my values and display it to the virtual column "price".
    Something like
    case
    when Working_Place = 'Office' and Mandatory=1
         then ...
    else '0.00'
    end as PRICE
    Or is it not possible?
    Edited by: DB2000 on 12.03.2013 05:09

    Use CASE:
    select  start_dt,
            end_dt,
            working_place,
            mandatory,
            case
              when working_place = 'Office' and mandatory = 0 then (end_dt - start_dt) * 25
              when working_place = 'Office' and mandatory = 1 then (end_dt - start_dt) * 20.60
              else 0
            end price
      from  tbl
    START_DT  END_DT    WORKING_PLA  MANDATORY      PRICE
    01-JAN-13 11-JAN-13 Office               1        206
    14-JAN-13 25-JAN-13 Home Office          0          0
    04-MAR-13 15-MAR-13 Office               0        275
    11-FEB-13 22-FEB-13 Office               1      226.6
    SQL> SY.

  • Tuning SQL query with SDO and Contains?

    I'trying to optimize a query
    with a sdo_filter and an intermedia_contains
    on a 3.000.000 records table,
    the query look like this
    SELECT COUNT(*) FROM professionnel WHERE mdsys.sdo_filter(professionnel.coor_cart,mdsys.sdo_geometry(2003, null, null,mdsys.sdo_elem_info_array(1,1003,4),mdsys.sdo_ordinate_array(809990,2087279,778784,2087279,794387,2102882)),'querytype=window') = 'TRUE' AND professionnel.code_rubr ='12 3 30' AND CONTAINS(professionnel.Ctx,'PLOMBERIE within Nom and ( RUE within Adresse1 )',1)>0
    and it takes 15s on a bi 750 pentium III with
    1.5Go of memory running under 8.1.6 linux.
    What can i do to improve this query time?
    null

    Hi Vincent,
    We have patches for Oracle 8.1.6 Spatial
    on NT and Solaris.
    These patches include bug fixes and
    performance enhancements.
    We are in the process of making these patches
    avaialble in a permanent place, but until then, I will temporarily put the patches on:
    ftp://oracle-ftp.oracle.com/
    Log in as anonymous and use your email for
    password.
    The patches are in /tmp/outgoing in:
    NT816-000706.zip - NT patch
    libordsdo.tar - Solaris patch
    I recommend doing some analysis on
    individual pieces of the query.
    i.e. time the following:
    1)
    SELECT COUNT(*)
    FROM professionnel
    WHERE mdsys.sdo_filter(
    professionnel.coor_cart,
    mdsys.sdo_geometry(
    2003, null, null,
    mdsys.sdo_elem_info_array(1,1003,4),
    mdsys.sdo_ordinate_array(
    809990,2087279,
    778784,2087279,
    794387,2102882)),
    'querytype=window') = 'TRUE';
    2)
    SELECT COUNT(*)
    FROM professionnel
    WHERE CONTAINS(professionnel.Ctx,
    'PLOMBERIE within Nom and ( RUE within Adresse1)',1) >0;
    You might want to try reorganizing the entire
    query as follows (no promises).
    If you contact me directly, I can try to
    help to further tune the SQL.
    Hope this helps. Thanks.
    Dan
    select count(*)
    FROM
    (SELECT /*+ no_merge */ rowid
    FROM professionnel
    WHERE mdsys.sdo_filter(
    professionnel.coor_cart,
    mdsys.sdo_geometry(
    2003, null, null,
    mdsys.sdo_elem_info_array(1,1003,4),
    mdsys.sdo_ordinate_array(809990,2087279,
    778784,2087279,
    794387,2102882)),
    'querytype=window') = 'TRUE'
    ) a,
    (SELECT /*+ no_merge */ rowid
    FROM professionnel
    WHERE CONTAINS(professionnel.Ctx,
    'PLOMBERIE within Nom and
    ( RUE within Adresse1)',1) >0
    ) b
    where a.rowid = b.rowid
    and professionnel.code_rubr ='12 3 30';
    **NOTE** Try this with no index on code_rubr
    null

  • SQL Query with Distinct and Count is wrong.

    Hello,
    i have another problem with a query.
    Here the Data:
    Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    CREATE      TABLE      TABLE_1
    (       "ORDER_NR"        VARCHAR2 (12)
    ,        "PRIORITY"        VARCHAR2 (2)
    ,        "WO_STATUS"        VARCHAR2 (1)
    ,        "STATUS_DATE"        DATE
    ,       "ART_NR"                      VARCHAR2 (9)
    ,       "DESCRIPTION"      VARCHAR2 (255)
    ,                 "PRICE"                     VARCHAR2 (10)
    CREATE      TABLE      TABLE_2
    (     "ART_NR"            VARCHAR(9)
    ,     "MODELL"              VARCHAR2(10)
    ,     "MANUFACT"         VARCHAR2(20)
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300612',     '12',     'U',        TO_DATE('05-FEB-13 10:22:39','DD-MON-RR HH24:MI:SS'),     '005231987',     '1ST ANNUAL SERVICE',   '5000.2546');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300638',     '05',     'U',        TO_DATE('05-FEB-13 11:38:39','DD-MON-RR HH24:MI:SS'),     '005667821',     '3RD ANNUAL SERVICE',   '5269.7856');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300638',     '12',     'U',        TO_DATE('06-FEB-13 12:38:39','DD-MON-RR HH24:MI:SS'),     '005667821',     '1ST BIENNIAL SERVICE', '1234.4468');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300638',     '12',     'U',        TO_DATE('07-FEB-13 13:38:39','DD-MON-RR HH24:MI:SS'),     '005667821',     '3RD ANNUAL SERVICE',   '4366.7856');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300762',     '12',     'U',        TO_DATE('22-FEB-13 14:55:48','DD-MON-RR HH24:MI:SS'),     '018743356',     '3RD ANNUAL SERVICE',   '4462.8632');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300766',     '12',     'U',        TO_DATE('22-FEB-13 08:32:13','DD-MON-RR HH24:MI:SS'),     '018743356',     '2ND ANNUAL SERVICE',   '8762.6643');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300766',     '05',     'U',        TO_DATE('23-FEB-13 12:32:13','DD-MON-RR HH24:MI:SS'),     '018743356',     '1ST BIENNIAL SERVICE', '3425.6643');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300766',     '12',     'U',        TO_DATE('24-FEB-13 14:32:13','DD-MON-RR HH24:MI:SS'),     '018743356',     '2ND BIENNIAL SERVICE', '6678.6643');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300612',     '12',     'U',        TO_DATE('06-FEB-13 10:22:39','DD-MON-RR HH24:MI:SS'),     '005231987',     '1ST ANNUAL SERVICE',   '5000.2546');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300638',     '05',     'U',        TO_DATE('05-FEB-13 11:38:39','DD-MON-RR HH24:MI:SS'),     '005667821',     '3RD ANNUAL SERVICE',   '5269.7856');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300638',     '12',     'U',        TO_DATE('06-FEB-13 12:38:39','DD-MON-RR HH24:MI:SS'),     '005667821',     '1ST BIENNIAL SERVICE', '1234.4468');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300638',     '12',     'U',        TO_DATE('07-FEB-13 13:38:39','DD-MON-RR HH24:MI:SS'),     '005667821',     '3RD ANNUAL SERVICE',   '4366.7856');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300762',     '12',     'U',        TO_DATE('22-FEB-13 14:55:48','DD-MON-RR HH24:MI:SS'),     '018743356',     '3RD ANNUAL SERVICE',   '4462.8632');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300766',     '12',     'U',        TO_DATE('22-FEB-13 08:32:13','DD-MON-RR HH24:MI:SS'),     '018743356',     '2ND ANNUAL SERVICE',   '8762.6643');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300766',     '05',     'U',        TO_DATE('23-FEB-13 12:32:13','DD-MON-RR HH24:MI:SS'),     '018743356',     '1ST BIENNIAL SERVICE', '3425.6643');
    INSERT      INTO      TABLE_1      (ORDER_NR,              PRIORITY, WO_STATUS,  STATUS_DATE,                                             ART_NR,           DESCRIPTION,            PRICE)
                  VALUES           ('1KKA1Z300766',     '12',     'U',        TO_DATE('24-FEB-13 14:32:13','DD-MON-RR HH24:MI:SS'),     '018743356',     '2ND BIENNIAL SERVICE', '6678.6643');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT1');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT2');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT3');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT4');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT5');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT6');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005667821',     'LASER',          'MANUFACT1');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005667821',     'LASER',          'MANUFACT2');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005667821',     'LASER',          'MANUFACT3');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005667821',     'LASER',          'MANUFACT4');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT1');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT2');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT3');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT4');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT5');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT6');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT1');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT2');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT3');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT4');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT5');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005231987',     'X-RAY1',          'MANUFACT6');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005667821',     'LASER',          'MANUFACT1');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005667821',     'LASER',          'MANUFACT2');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005667821',     'LASER',          'MANUFACT3');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('005667821',     'LASER',          'MANUFACT4');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT1');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT2');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT3');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT4');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT5');
    INSERT     INTO      TABLE_2      (ART_NR,            MODELL,         MANUFACT)
                  VALUES           ('018743356',     'VACCUM',          'MANUFACT6');
    COMMIT;And my query:
    SELECT T1.ART_NR
    , T2.MODELL
    , SUM(ROUND(T1.PRICE, 2)) AS TOTAL_PRICE
    , COUNT(*) AS QTY
    , TO_CHAR(T1.STATUS_DATE, 'MON-RR') AS MONTH
    FROM TABLE_1 T1, TABLE_2 T2
    WHERE T1.WO_STATUS = 'U'
    AND T1.ART_NR = T2.ART_NR
    AND TO_CHAR(T1.STATUS_DATE, 'MON-RR') = 'FEB-13'
    GROUP BY T2.MODELL
    , T1.ART_NR
    , TO_CHAR(T1.STATUS_DATE, 'MON-RR')And the result:
    ART_NR      MODELL     TOTAL_PRICE        QTY     MONTH
    018743356 VACCUM     559916.16            96        FEB-13
    005667821 LASER        173936.48            48        FEB-13
    005231987 X-RAY1          120006             24        FEB-13My problem now is, the OTY field ist wrong it should count how often the equipment was in service in FEB-13 and group it by "MODELL" the MANUFACT field is not interesting for me, but this ist my problem, one Modell can have multible Manufacter and so i got a wrong count for my QTY.
    The next step i need is to group the result also by Service type (annual or biennial), like this:
    ART_NR      MODELL     TOTAL_PRICE        QTY     MONTH   SERVICE_TYPE
    018743356 VACCUM      1234.56               4         FEB-13     ANNUAL
    018743356 VACCUM      4423.48               10       FEB-13     BIENNIAL
    005667821 LASER         4783.11               2         FEB-13     ANNUAL
    005667821 LASER         1123.77               22       FEB-13      BIENNIAL
    005231987 X-RAY1        8966.12               6        FEB-13      ANNUAL
    005231987 X-RAY1        7826.44              12        FEB-13      BIENNIALThis values are only out of my head, not the table, only to show what i need.
    Thanks for your help.
    Greets Reinhard

    Hi,
    Here's one way:
    WITH    got_groups  AS
         SELECT  art_nr
         ,     TRUNC (status_date, 'MONTH')     AS month
         ,     CASE
                  WHEN  UPPER (description) LIKE '%ANNUAL%'
                                         THEN  'ANNUAL'
                  WHEN  UPPER (description) LIKE '%BIENNIAL%'
                                         THEN  'BIENNIAL'
              END                    AS service_type
         ,     TO_NUMBER (price)          AS price
         FROM     table_1
         WHERE     status_date     >= DATE '2013-02-01'
         AND     status_date     <  DATE '2013-03-01'
    ,       table_2_summary  AS
         SELECT DISTINCT       art_nr, modell
         FROM               table_2
    SELECT       g.art_nr
    ,       s.modell
    ,       ROUND ( SUM (g.price)
              , 2
              )          AS total_price
    ,       COUNT (*)          AS qty
    ,       g.month
    ,       service_type
    FROM       got_groups       g
    JOIN       table_2_summary  s     ON  s.art_nr  = g.art_nr 
    GROUP BY  g.art_nr
    ,            s.modell
    ,            g.month
    ,       g.service_type
    ;The reason why your aggregates were originally too high is that you have a many-to-many relationship between the tables. The tables are related only by art_nr, but art_nr is not unique in either table. Look at art_nr '005231987', example. There ate 2 rows in table_1 with that art_nr, and 6 rows in table_2 with the same art_nr. If we join on art_nr, then both of the rows in table_1 will match each of the 6 rows in table_2, so the COUNT will be 2 * 6 = 12, and in the SUM, each of the numbers from table_1 will get added 6 times.
    Why is table_2 designed the way it is? Cn there be multiple modells for the same art_nr? If so, what would you want for output? If there can only be 1 modell for each art_nr, then a better design would be to have a table that just had one row per art_nr, and included the modell column, and another table to show which manufacturers produce each art_nr. In this problem, you wouldn't need the manufacturers table, and the other table already has unique art_nrs, so you wouldn't need anything like the sub-query table_2_summary.
    Don't store price in a VARCHAR2 column. Storing NUMBERs in a VARCHAR2 column is just asking for problems. Why not use a NUMBER column instead.
    You'll notice that I used ROUND (SUM ... where you use SUM ( ROUND. The results might be a little different because of rounding errors. ROUND ( SUM only has to call ROUND once per group (5 times in this example) instead of once per row (16 times in this example). The less rounding you do, the less rounding error creeps in. Also, since there are fewer function calls, it's more convenient. (Of course, you'll never notice the difference between calling ROUND 5 times or 16 times, but in a real-life exampe, the difference could be between calling it 50 times or calling it 16000 times.) If you really need to use SUM (ROUND, you can.

  • ORACLE SQL Query with Parent and Child structure

    I have 2 tables which are Account tbl and Customer tbl, the structure is like below:
    Account tbl
    Customer_ID    Account_ID    Parent_Account_ID    
    3780952        3780952         3780952
    3780997        3780997         3780997
    3781004        3781004         3780997
    Customer tbl (Customer_Group have different value, but im only interest on Personal)
    Customer_ID      Customer_Group
    3781004          Personal
    3780997          Personal
    3780952          PersonalThe rule to determine PS/NonPS, Principle, Supp as per below:
    **PS/NonPs**
    Customer_ID equal to Parent_Account and Parent_Account is unique (not exist more than 1)  then NonPs.
    Customer_ID equal to Parent_Account and Parent_Account is non unique OR -   Customer_ID is not equal to Parent_Account then PS    
    **Principle**  IF NonPS then Principle is Null IF PS - If Customer_ID equal to Parent_Account then Principle is Y else N
    **Supp** IF NonPS then Supp is Null IF PS - If Customer_ID not equal to Parent_Account then supp is Y else N The final output should be like this
    Customer_ID    Account_ID    Parent_Account_ID   PS/NonPS   Principle   Supp
    3780952        3780952       3780952             NonPS       Null        Null
    3780997        3780997       3780997             PS          Y           N
    3781004        3781004       3780997             PS          N           Y I alredy tried many times but still cant get the output..anyone can help ?

    hi,
    i hope this is what you want , this query matches all of your mentioned requirements .
    WITH accounts AS
         (SELECT 3780952 AS customer_id, 3780952 AS account_id,
                 3780952 AS parent_account_id
            FROM DUAL
          UNION ALL
          SELECT 3780997 AS customer_id, 3780997 AS account_id,
                 3780997 AS parent_account_id
            FROM DUAL
          UNION ALL
          SELECT 3781004 AS customer_id, 3781004 AS account_id,
                 3780997 AS parent_account_id
            FROM DUAL),
         customer AS
         (SELECT 3781004 AS customer_id, 'Personal' AS customer_group
            FROM DUAL
          UNION ALL
          SELECT 3780997 AS customer_id, 'Personal' AS customer_group
            FROM DUAL
          UNION ALL
          SELECT 3780952 AS customer_id, 'Personal' AS customer_group
            FROM DUAL)
    SELECT customer_id, account_id, parent_account_id, "PS/NonPS",
           CASE
              WHEN "PS/NonPS" = 'NonPS'
                 THEN NULL
              WHEN customer_id = parent_account_id
                 THEN 'Y'
              WHEN customer_id <> parent_account_id
                 THEN 'N'
           END principle,
           CASE
              WHEN "PS/NonPS" = 'NonPS'
                 THEN NULL
              WHEN "PS/NonPS" = 'PS' AND customer_id <> parent_account_id
                 THEN 'Y'
              WHEN "PS/NonPS" = 'PS' AND customer_id = parent_account_id
                 THEN 'N'
           END SUM
      FROM (SELECT   t1.customer_id, t1.account_id, t1.parent_account_id,
                     CASE
                        WHEN t1.customer_id = t1.parent_account_id
                        AND (SELECT COUNT (*)
                               FROM accounts
                              WHERE parent_account_id = t1.parent_account_id) = 1
                           THEN 'NonPS'
                        ELSE 'PS'
                     END "PS/NonPS"
                FROM accounts t1, customer t2
               WHERE t1.customer_id = t2.customer_id
            ORDER BY t1.customer_id)
    output
    CUSTOMER_ID     ACCOUNT_ID     PARENT_ACCOUNT_ID     PS/NonPS     PRINCIPLE     SUM
    3780952     3780952     3780952     NonPS          
    3780997     3780997     3780997     PS     Y     N
    3781004     3781004     3780997     PS     N     YThanks,
    P Prakash
    Edited by: prakash on Jan 17, 2012 3:38 AM

  • SQL query with Bind variable with slower execution plan

    I have a 'normal' sql select-insert statement (not using bind variable) and it yields the following execution plan:-
    Execution Plan
    0 INSERT STATEMENT Optimizer=CHOOSE (Cost=7 Card=1 Bytes=148)
    1 0 HASH JOIN (Cost=7 Card=1 Bytes=148)
    2 1 TABLE ACCESS (BY INDEX ROWID) OF 'TABLEA' (Cost=4 Card=1 Bytes=100)
    3 2 INDEX (RANGE SCAN) OF 'TABLEA_IDX_2' (NON-UNIQUE) (Cost=3 Card=1)
    4 1 INDEX (FAST FULL SCAN) OF 'TABLEB_IDX_003' (NON-UNIQUE)
    (Cost=2 Card=135 Bytes=6480)
    Statistics
    0 recursive calls
    18 db block gets
    15558 consistent gets
    47 physical reads
    9896 redo size
    423 bytes sent via SQL*Net to client
    1095 bytes received via SQL*Net from client
    3 SQL*Net roundtrips to/from client
    1 sorts (memory)
    0 sorts (disk)
    55 rows processed
    I have the same query but instead running using bind variable (I test it with both oracle form and SQL*plus), it takes considerably longer with a different execution plan:-
    Execution Plan
    0 INSERT STATEMENT Optimizer=CHOOSE (Cost=407 Card=1 Bytes=148)
    1 0 TABLE ACCESS (BY INDEX ROWID) OF 'TABLEA' (Cost=3 Card=1 Bytes=100)
    2 1 NESTED LOOPS (Cost=407 Card=1 Bytes=148)
    3 2 INDEX (FAST FULL SCAN) OF TABLEB_IDX_003' (NON-UNIQUE) (Cost=2 Card=135 Bytes=6480)
    4 2 INDEX (RANGE SCAN) OF 'TABLEA_IDX_2' (NON-UNIQUE) (Cost=2 Card=1)
    Statistics
    0 recursive calls
    12 db block gets
    3003199 consistent gets
    54 physical reads
    9448 redo size
    423 bytes sent via SQL*Net to client
    1258 bytes received via SQL*Net from client
    3 SQL*Net roundtrips to/from client
    1 sorts (memory)
    0 sorts (disk)
    55 rows processed
    TABLEA has around 3million record while TABLEB has 300 records. Is there anyway I can improve the speed of the sql query with bind variable? I have DBA Access to the database
    Regards
    Ivan

    Many thanks for your reply.
    I have run the statistic already for the both tableA and tableB as well all the indexes associated with both table (using dbms_stats, I am on 9i db ) but not the indexed columns.
    for table I use:-
    begin
    dbms_stats.gather_table_stats(ownname=> 'IVAN', tabname=> 'TABLEA', partname=> NULL);
    end;
    for index I use:-
    begin
    dbms_stats.gather_index_stats(ownname=> 'IVAN', indname=> 'TABLEB_IDX_003', partname=> NULL);
    end;
    Is it possible to show me a sample of how to collect statisc for INDEX columns stats?
    regards
    Ivan

  • How to compare result from sql query with data writen in html input tag?

    how to compare result
    from sql query with data
    writen in html input tag?
    I need to compare
    user and password in html form
    with all user and password in database
    how to do this?
    or put the resulr from sql query
    in array
    please help me?

    Hi dejani
    first get the user name and password enter by the user
    using
    String sUsername=request.getParameter("name of the textfield");
    String sPassword=request.getParameter("name of the textfield");
    after executeQuery() statement
    int exist=0;
    while(rs.next())
    String sUserId= rs.getString("username");
    String sPass_wd= rs.getString("password");
    if(sUserId.equals(sUsername) && sPass_wd.equals(sPassword))
    exist=1;
    if(exist==1)
    out.println("user exist");
    else
    out.println("not exist");

  • How could I replace hard coded value in my sql query with constant value?

    Hi all,
    Could anyone help me how to replace hardcoded value in my sql query with constant value that might be pre defined .
    PROCEDURE class_by_day_get_bin_data
         in_report_parameter_id   IN   NUMBER,
         in_site_id               IN   NUMBER,
         in_start_date_time       IN   TIMESTAMP,
         in_end_date_time         IN   TIMESTAMP,
         in_report_level_min      IN   NUMBER,
         in_report_level_max      IN   NUMBER
    IS
      bin_period_length   NUMBER(6,0); 
    BEGIN
      SELECT MAX(period_length)
         INTO bin_period_length
        FROM bin_data
         JOIN site_to_data_source_lane_v
           ON bin_data.data_source_id = site_to_data_source_lane_v.data_source_id
         JOIN bin_types
           ON bin_types.bin_type = bin_data.bin_type 
       WHERE site_to_data_source_lane_v.site_id = in_site_id
         AND bin_data.start_date_time     >= in_start_date_time - numtodsinterval(1, 'DAY')
         AND bin_data.start_date_time     <  in_end_date_time   + numtodsinterval(1, 'DAY')
         AND bin_data.bin_type            =  2
         AND bin_data.period_length       <= 60;
      --Clear the edr_class_by_day_bin_data temporary table and populate it with the data for the requested
      --report.
      DELETE FROM edr_class_by_day_bin_data;
       SELECT site_to_data_source_lane_v.site_id,
             site_to_data_source_lane_v.site_lane_id,
             site_to_data_source_lane_v.site_direction_id,
             site_to_data_source_lane_v.site_direction_name,
             bin_data_set.start_date_time,
             bin_data_set.end_date_time,
             bin_data_value.bin_id,
             bin_data_value.bin_value
        FROM bin_data
        JOIN bin_data_set
          ON bin_data.bin_serial = bin_data_set.bin_serial
        JOIN bin_data_value
          ON bin_data_set.bin_data_set_serial = bin_data_value.bin_data_set_serial
        JOIN site_to_data_source_lane_v
             ON bin_data.data_source_id = site_to_data_source_lane_v.data_source_id
            AND bin_data_set.lane = site_to_data_source_lane_v.data_source_lane_id
        JOIN (
               SELECT CAST(report_parameter_value AS NUMBER) lane_id
                 FROM report_parameters
                WHERE report_parameters.report_parameter_id    = in_report_parameter_id
                  AND report_parameters.report_parameter_group = 'LANE'
                  AND report_parameters.report_parameter_name  = 'LANE'
             ) report_lanes
          ON site_to_data_source_lane_v.site_lane_id = report_lanes.lane_id
        JOIN (
               SELECT CAST(report_parameter_value AS NUMBER) class_id
                 FROM report_parameters
                WHERE report_parameters.report_parameter_id    = in_report_parameter_id
                  AND report_parameters.report_parameter_group = 'CLASS'
                  AND report_parameters.report_parameter_name  = 'CLASS'
             ) report_classes
          ON bin_data_value.bin_id = report_classes.class_id
        JOIN edr_rpt_tmp_inclusion_table
          ON TRUNC(bin_data_set.start_date_time) = TRUNC(edr_rpt_tmp_inclusion_table.date_time)
       WHERE site_to_data_source_lane_v.site_id = in_site_id
         AND bin_data.start_date_time     >= in_start_date_time - numtodsinterval(1, 'DAY')
         AND bin_data.start_date_time     <  in_end_date_time   + numtodsinterval(1, 'DAY')
         AND bin_data_set.start_date_time >= in_start_date_time
         AND bin_data_set.start_date_time <  in_end_date_time
         AND bin_data.bin_type            =  2
         AND bin_data.period_length       =  bin_period_length;
    END class_by_day_get_bin_data;In the above code I'm using the hard coded value 2 for bin type
    bin_data.bin_type            =  2But I dont want any hard coded number or string in the query.
    How could I replace it?
    I defined conatant value like below inside my package body where the actual procedure comes.But I'm not sure whether I have to declare it inside package body or inside the procedure.
    bin_type     CONSTANT NUMBER := 2;But it does't look for this value. So I'm not able to get desired value for the report .
    Thanks.
    Edited by: user10641405 on May 29, 2009 1:38 PM

    Declare the constant inside the procedure.
    PROCEDURE class_by_day_get_bin_data(in_report_parameter_id IN NUMBER,
                                        in_site_id             IN NUMBER,
                                        in_start_date_time     IN TIMESTAMP,
                                        in_end_date_time       IN TIMESTAMP,
                                        in_report_level_min    IN NUMBER,
                                        in_report_level_max    IN NUMBER) IS
      bin_period_length NUMBER(6, 0);
      v_bin_type     CONSTANT NUMBER := 2;
    BEGIN
      SELECT MAX(period_length)
        INTO bin_period_length
        FROM bin_data
        JOIN site_to_data_source_lane_v ON bin_data.data_source_id =
                                           site_to_data_source_lane_v.data_source_id
        JOIN bin_types ON bin_types.bin_type = bin_data.bin_type
       WHERE site_to_data_source_lane_v.site_id = in_site_id
         AND bin_data.start_date_time >=
             in_start_date_time - numtodsinterval(1, 'DAY')
         AND bin_data.start_date_time <
             in_end_date_time + numtodsinterval(1, 'DAY')
         AND bin_data.bin_type = v_bin_type
         AND bin_data.period_length <= 60;
      --Clear the edr_class_by_day_bin_data temporary table and populate it with the data for the requested
      --report.
      DELETE FROM edr_class_by_day_bin_data;
      INSERT INTO edr_class_by_day_bin_data
        (site_id,
         site_lane_id,
         site_direction_id,
         site_direction_name,
         bin_start_date_time,
         bin_end_date_time,
         bin_id,
         bin_value)
        SELECT site_to_data_source_lane_v.site_id,
               site_to_data_source_lane_v.site_lane_id,
               site_to_data_source_lane_v.site_direction_id,
               site_to_data_source_lane_v.site_direction_name,
               bin_data_set.start_date_time,
               bin_data_set.end_date_time,
               bin_data_value.bin_id,
               bin_data_value.bin_value
          FROM bin_data
          JOIN bin_data_set ON bin_data.bin_serial = bin_data_set.bin_serial
          JOIN bin_data_value ON bin_data_set.bin_data_set_serial =
                                 bin_data_value.bin_data_set_serial
          JOIN site_to_data_source_lane_v ON bin_data.data_source_id =
                                             site_to_data_source_lane_v.data_source_id
                                         AND bin_data_set.lane =
                                             site_to_data_source_lane_v.data_source_lane_id
          JOIN (SELECT CAST(report_parameter_value AS NUMBER) lane_id
                  FROM report_parameters
                 WHERE report_parameters.report_parameter_id =
                       in_report_parameter_id
                   AND report_parameters.report_parameter_group = 'LANE'
                   AND report_parameters.report_parameter_name = 'LANE') report_lanes ON site_to_data_source_lane_v.site_lane_id =
                                                                                         report_lanes.lane_id
          JOIN (SELECT CAST(report_parameter_value AS NUMBER) class_id
                  FROM report_parameters
                 WHERE report_parameters.report_parameter_id =
                       in_report_parameter_id
                   AND report_parameters.report_parameter_group = 'CLASS'
                   AND report_parameters.report_parameter_name = 'CLASS') report_classes ON bin_data_value.bin_id =
                                                                                            report_classes.class_id
          JOIN edr_rpt_tmp_inclusion_table ON TRUNC(bin_data_set.start_date_time) =
                                              TRUNC(edr_rpt_tmp_inclusion_table.date_time)
         WHERE site_to_data_source_lane_v.site_id = in_site_id
           AND bin_data.start_date_time >=
               in_start_date_time - numtodsinterval(1, 'DAY')
           AND bin_data.start_date_time <
               in_end_date_time + numtodsinterval(1, 'DAY')
           AND bin_data_set.start_date_time >= in_start_date_time
           AND bin_data_set.start_date_time < in_end_date_time
           AND bin_data.bin_type = v_bin_type
           AND bin_data.period_length = bin_period_length;
    END class_by_day_get_bin_data;

  • Need complex query  with joins and AGGREGATE  functions.

    Hello Everyone ;
    Good Morning to all ;
    I have 3 tables with 2 lakhs record. I need to check query performance.. How CBO rewrites my query in materialized view ?
    I want to make complex join with AGGREGATE FUNCTION.
    my table details
    SQL> select from tab;*
    TNAME TABTYPE CLUSTERID
    DEPT TABLE
    PAYROLL TABLE
    EMP TABLE
    SQL> desc emp
    Name
    EID
    ENAME
    EDOB
    EGENDER
    EQUAL
    EGRADUATION
    EDESIGNATION
    ELEVEL
    EDOMAIN_ID
    EMOB_NO
    SQL> desc dept
    Name
    EID
    DNAME
    DMANAGER
    DCONTACT_NO
    DPROJ_NAME
    SQL> desc payroll
    Name
    EID
    PF_NO
    SAL_ACC_NO
    SALARY
    BONUS
    I want to make  complex query  with joins and AGGREGATE  functions.
    Dept names are : IT , ITES , Accounts , Mgmt , Hr
    GRADUATIONS are : Engineering , Arts , Accounts , business_applications
    I want to select records who are working in IT and ITES and graduation should be "Engineering"
    salary > 20000 and < = 22800 and bonus > 1000 and <= 1999 with count for males and females Separately ;
    Please help me to make a such complex query with joins ..
    Thanks in advance ..
    Edited by: 969352 on May 25, 2013 11:34 AM

    969352 wrote:
    why do you avoid providing requested & NEEDED details?I do NOT understand what do you expect ?
    My Goal is :
    1. When executing my own query i need to check expalin plan.please proceed to do so
    http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9010.htm#SQLRF01601
    2. IF i enable query rewrite option .. i want to check explain plan ( how optimizer rewrites my query ) ? please proceed to do so
    http://docs.oracle.com/cd/E11882_01/server.112/e16638/ex_plan.htm#PFGRF009
    3. My only aim is QUERY PERFORMANCE with QUERY REWRITE clause in materialized view.It is an admirable goal.
    Best Wishes on your quest for performance improvements.

  • Need help with SQL Query with Inline View + Group by

    Hello Gurus,
    I would really appreciate your time and effort regarding this query. I have the following data set.
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*20.00*-------------19
    1234567----------11223--------------7/5/2008-----------Adjustment for bad quality---------44345563------------------A-----------------10.00------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765--------------------I---------------------30.00-------------19
    Please Ignore '----', added it for clarity
    I am trying to write a query to aggregate paid_amount based on Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number and display description with Invoice_type 'I' when there are multiple records with the same Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number. When there are no multiple records I want to display the respective Description.
    The query should return the following data set
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*10.00*------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765-------------------I---------------------30.00--------------19
    The following is my query. I am kind of lost.
    select B.Description, A.sequence_id,A.check_date, A.check_number, A.invoice_number, A.amount, A.vendor_number
    from (
    select sequence_id,check_date, check_number, invoice_number, sum(paid_amount) amount, vendor_number
    from INVOICE
    group by sequence_id,check_date, check_number, invoice_number, vendor_number
    ) A, INVOICE B
    where A.sequence_id = B.sequence_id
    Thanks,
    Nick

    It looks like it is a duplicate thread - correct me if i'm wrong in this case ->
    Need help with SQL Query with Inline View + Group by
    Regards.
    Satyaki De.

  • Extract Sql Query with Actual Parameters from Report

    Hi
    I am able to extract query from Crystal Report using the following code :
    ReportDocument.ReportClientDocument.RowSetController.GetSqlStatement(new GroupPath, out tmp);
    But the sql query retrieve comes in the following format :
    select name , trans_code, account_code from command_query.accounts
    where account_code = {?Command_query_Prompt0}  and effective_date < '{?Command_query_prompt1 }'
    The parameters which I m using in the reports are :
    Account_Code and Effective_Date .
    Why does my extracted sql translates it into {?Command_query_Prompt0} and '{?Command_query_prompt1 }' .
    Is there any way to map this to the actual parameter values ?
    OR
    Can we extract the query after assigning the values ?
    Any help is appreciated ... 
    Thanks
    Sanchet

    hi,
    You can create nested sql query with conditional parameters,
    For example
    Select Code From OITT Where Code IN (Select ItemCode From OITM
    Where ItemName LIKE '[%0]' + '%%')
    Edited by: Jeyakanthan A on Jun 9, 2009 12:31 PM

  • Hosting company does not support SQL query with OUTFILE clause

    From my mysql database, I want to allow the user to run a query and produce a csv / text file of our membership database.   Unfortunately,  I just found out my hosting company does not support the SQL query with OUTFILE clause for MySQL database.
    Are there any other options available to produce a file besides me running the query in phpadmin and making the file available to users.
    Thanks.  George

    Maybe this external Export Mysql data to CSV - PHP tutorial will be of help
    Cheers,
    Günter

  • CAML Query with 10 AND conditions

    Hello,
    I need some help with a CAML query. This particular query needs to have 10 AND conditions. Quite frankly, with all the nesting it is driving me a little nuts:
    What I have is:
    <Query>
    <Where>
    <And>
    <And>
    <And>
    <And>
    <And>
    <And>
    <And>
    <And>
    <And>
    <Eq><FieldRef Name='Column1' LookupId='TRUE' /><Value Type='Text'>10341</Value></Eq>
    <Eq><FieldRef Name='Column2' LookupId='TRUE' /><Value Type='Text'>9539</Value></Eq>
    </And>
    <Eq><FieldRef Name='Column3' LookupId='TRUE' /><Value Type='Text'>183</Value></Eq>
    </And>
    <Eq><FieldRef Name='Column4' LookupId='TRUE' /><Value Type='Text'>35</Value></Eq>
    </And>
    <IsNull><FieldRef Name='Column5' /></IsNull>
    </And>
    <Eq><FieldRef Name='Column6' LookupId='TRUE' /><Value Type='Text'>4387</Value></Eq>
    </And>
    <Eq><FieldRef Name='Column7' LookupId='TRUE' /><Value Type='Text'>4204</Value></Eq>
    </And>
    <Eq><FieldRef Name='Column8' LookupId='TRUE' /><Value Type='Text'>36</Value></Eq>
    </And>
    <Eq><FieldRef Name='Column9' LookupId='TRUE' /><Value Type='Text'>213</Value></Eq>
    </And>
    <IsNull><FieldRef Name='Column10' /></IsNull>
    </And>
    </Where>
    </Query>
    I have added this into my ItemAdding Event Receiver as it will basically do a check for duplicate items based on the 10 columns. 
    If anyone can help guide me in this, it would be much appreciated. I have been using a CAML Query Builder to help.

    http://webcache.googleusercontent.com/search?q=cache:xji7jOxa5_EJ:aasai-sharepoint.blogspot.com/2013/02/caml-query-with-multiple-conditions.html+&cd=3&hl=en&ct=clnk&gl=in
    http://stackoverflow.com/questions/6203821/caml-query-with-nested-ands-and-ors-for-multiple-fields
    Since you are not allowed to put more than two conditions in one condition group (And | Or) you have to create an extra nested group (MSDN). The expression
    A AND B AND C looks like this:
    <And>
    A
    <And>
    B
    C
    </And>
    </And>
    Your SQL like sample translated to CAML (hopefully with matching XML tags ;) ):
    <Where>
    <And>
    <Or>
    <Eq>
    <FieldRef Name='FirstName' />
    <Value Type='Text'>John</Value>
    </Eq>
    <Or>
    <Eq>
    <FieldRef Name='LastName' />
    <Value Type='Text'>John</Value>
    </Eq>
    <Eq>
    <FieldRef Name='Profile' />
    <Value Type='Text'>John</Value>
    </Eq>
    </Or>
    </Or>
    <And>
    <Or>
    <Eq>
    <FieldRef Name='FirstName' />
    <Value Type='Text'>Doe</Value>
    </Eq>
    <Or>
    <Eq>
    <FieldRef Name='LastName' />
    <Value Type='Text'>Doe</Value>
    </Eq>
    <Eq>
    <FieldRef Name='Profile' />
    <Value Type='Text'>Doe</Value>
    </Eq>
    </Or>
    If this helped you resolve your issue, please mark it Answered

  • How to write sql query with many parameter in ireport

    hai,
    i'm a new user in ireport.how to write sql query with many parameters in ireport's report query?i already know to create a parameter like(select * from payment where entity=$P{entity}.
    but i don't know to create query if more than 1 parameter.i also have parameter such as
    $P{entity},$P{id},$P{ic}.please help me for this.
    thanks

    You are in the wrong place. The ireport support forum may be found here
    http://www.jasperforge.org/index.php?option=com_joomlaboard&Itemid=215&func=showcat&catid=9

Maybe you are looking for

  • Error in restoring a database

    Hi, I can't able to restore a database, below is the error,please help me out? TITLE: Microsoft SQL Server Management Studio Restore failed for Server 'xxxxx'.  (Microsoft.SqlServer.SmoExtended) For help, click: http://go.microsoft.com/fwlink?ProdNam

  • How to install windows 7 on bootcamp without using super drive

    Hi All, I have just purchased a new MacBook Air mid-2011. I wish to install Windows 7 Ultimate on the boot camp partition but have not purchased any external drive. How can I install Windows using remote drive of my other MacBook running OSX-Lion or

  • Screen went black

    My macbook screen went completely black, but the cpu sitll works when I connect it to a monitor. Can the screen be repaired?

  • Regarding Reports: Changing fit-to-layout from A4 page to A3

    I need to print a report in A3 page format. Suppose I have the report setup for A4 and want to get its modification for A3. Could anybody give a hint at how do I expand layout in the layout editor.(the page frame doesn't fit to layout after I extend

  • Mail help please

    I have a frozen mail screen, the send and cancel buttons are both grey. Any ideas how to unfreeze? I can not get to the mail boxes or anything else behind. Any ideas please? Thank you!