Help Calculating in SQL

Hi,
I am using oracle 10g.
I want to build a sql that helps me keep track of all the stocks I've bought and sold. Provided that I sell same qty that I buy. Here is the scenarion I am looking at as my initial table and following is my result to achieve.
Here are all my actions Which I store in a table
ACTION    SMBL    QTY    PRICE    AMOUNT    COMM    STATUS
Sell    WFC    300    17.85         5355     7   Executed
Buy     WFC    100    13.9299   -1392.99     7   Executed
Buy     WFC    200    15.60        -3120     7   ExecutedHere is What I would like to achieve,
SMBL    QTY     AVG_BUY_PRICE       TOTAL_BUY_PRICE     AVG_SELL_PRICE      TOTAL_SELL_PRICE    P&L     P&L %
WFC     300       15.08996667           4526.99             17.82666667         5348            821.01 18.14%If someone can help me with something that would allow me buy and sell different qty and still keep track , that would be great....
Thanks.........

Hello,
Output from the above query
Copyright (c) 1982, 2007, Oracle.  All rights reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Production
With the Partitioning, Oracle Label Security, OLAP and Data Mining Scoring Engine options
SQL> set lines 400;
SQL> WITH t
  2         AS (  SELECT   smbl,
  3                        action,
  4                        SUM (qty) qty,
  5                        CASE WHEN action = 'Buy' THEN AVG (price) END
  6                           AS avg_buy_price,
  7                        CASE
  8                           WHEN action = 'Buy' THEN SUM (ABS (amount) + comm)
  9                        END
10                           AS total_buy_price,
11                        CASE WHEN action = 'Sell' THEN AVG (price) END
12                           AS avg_sell_price,
13                        CASE WHEN action = 'Sell' THEN SUM (amount - comm) END
14                           AS total_sell_price
15                 FROM   accounts
16             GROUP BY   smbl, action)
17    SELECT   smbl,
18             t.qty,
19             SUM (avg_buy_price) avg_buy_price,
20             SUM (total_buy_price) total_buy_price,
21             SUM (avg_sell_price) avg_sell_price,
22             SUM (total_sell_price) total_sell_price,
23             (SUM (total_sell_price) - SUM (total_buy_price)) AS "P_AND_L",
24            round( ((SUM (total_sell_price) - SUM (total_buy_price)) /  SUM (total_buy_price) ) * 100, 2) as "P_AND_L%"
25      FROM   t
26  GROUP BY   smbl, qty;
SMBL        QTY AVG_BUY_PRICE TOTAL_BUY_PRICE AVG_SELL_PRICE TOTAL_SELL_PRICE    P_AND_L   P_AND_L%
WFC         300      14.76495         4526.99          17.85             5348     821.01      18.14
SQL>

Similar Messages

  • Calculations Using SQL Query

    Hi All,
    I am using Oracle Database Version 11.2.
    I have a formula (A-B)/[(A-B)/10]. The tables that are holding the rows for this calculations are given below:
    ROWS_TAB
    ====== ===================
    Row          Amount
    ====== ===================
    A            5000
    B            -5000
    FORMULA_TAB
    ======== =========== ======== =============
    | ROW#  | Operator            | ROW        |   CONSTANT   |
    ======== =========== ======== =============
    | 10        |     E                   |      A       |                         |
    | 20        |     -                    |     B        |                         |
    | 30        |     E                   |      A       |                         |
    | 40        |     -                    |     B        |                         |
    | 50        |     /                    |               |      10                |
    | 60        |    /                     |               |                          |
    ======== =========== ======== =============
    The operator E starts a new calculation. The above formula has two sub-expressions thereby the table has two rows with E. Minus denoted by -, Plus denoted by +, Multiply denoted by *, and Division denoted by /.
    I want to write single SQL query to perform this calculation. Is it achievable in SQL?
    The scripts used to generate the tables are as below:
    create table ROWS_TAB
    (row_name VARCHAR2(1),
    amount NUMBER);
    create table FORMULA_TAB
    (row# NUMBER,
    operator VARCHAR2(1),
    row_name VARCHAR2(1),
    constant NUMBER);
    INSERT INTO ROWS_TAB VALUES('A', 5000);
    INSERT INTO ROWS_TAB VALUES('B', -5000);
    INSERT INTO FORMULA_TAB VALUES(10, 'E','A',null);
    INSERT INTO FORMULA_TAB VALUES(20, '-','B',null);
    INSERT INTO FORMULA_TAB VALUES(30, 'E','A',null);
    INSERT INTO FORMULA_TAB VALUES(40, '-','B',null);
    INSERT INTO FORMULA_TAB VALUES(50, '/','',10);
    INSERT INTO FORMULA_TAB VALUES(60, '/','','');
    Can anyone help in writing SQL query....
    Thanks in advance
    Best Regards
    Bilal

    As Frank said, it would be much easier to simply input the formula. Then, assuming you have OLAP option:
    variable formula varchar2(30)
    exec :formula := '(A-B)/((A-B)/10)';
    with t as (
               select  *
                 from  rows_tab
                 model
                   dimension by(row_number() over(order by row_name) r)
                   measures(
                            row_name,
                            amount,
                            count(*) over() cnt,
                            cast(:formula as varchar2(4000)) formula
                   rules(
                         formula[any] order by r = replace(nvl(formula[cv() - 1],formula[cv()]),row_name[cv()],amount[cv()])
    select  :formula || ' = ' || dbms_aw.eval_number(formula) result
      from  t
      where r = cnt
    RESULT
    (A-B)/((A-B)/10) = 10
    SQL>
    And if you do not have OLAP, you could use xquery:
    with t as (
               select  *
                 from  rows_tab
                 model
                   dimension by(row_number() over(order by row_name) r)
                   measures(
                            row_name,
                            amount,
                            count(*) over() cnt,
                            cast(:formula as varchar2(4000)) formula
                   rules(
                         formula[any] order by r = replace(nvl(formula[cv() - 1],formula[cv()]),row_name[cv()],amount[cv()])
    select  :formula || ' = ' || xmlquery(replace(formula,'/',' div ') returning content) result
      from  t
      where r = cnt
    RESULT
    (A-B)/((A-B)/10) = 10
    SQL>
    SY.

  • Help Needed in SQL QPAC

    Hi there,
    I need some help regarding the SQL QPAC which is a built in QPAC in Adobe Livecycle Workflow. The SQL QPAC takes MYSQL as the default database. Suppose if we need to connect to the SQL Server or any other database, what is the procedure to do that.
    Suraj

    Hi Suraj
    You need to deploy a second copy of the SQL QPAC, and point it at a different datasource. The datasource is defined as a deployment parameter (it will prompt you when you deploy the new version of the qpac).
    You will also need to define the datasource in your application server. This is done in different ways for different application servers - for details, please see: standards_based_qpacs.pdf (part of the Workflow SDK), page 12, "Creating a JNDI datasource".
    Alternately, you can try out our SQLPlus QPAC. This allows you to directly specify connection url, driver, username and password. The SQLPlus QPAC does a lot of other things that the regular SQL QPAC doesn't do, such as handling multiple rows, testing your query, and outputting the data in a variety of ways.
    Details at: http://www.avoka.com/avoka/qpac_library.shtml
    Howard

  • Help with an SQL Query on the Logger

    We are running UCCE 8.5(3) and need help with an SQL query. When I run the below I would also like to see skill group information(name preferably)? Any help would be greatly appreciated!
    select * from dbo.t_Termination_Call_Detail where DateTime between '10-11-2012 00:00:00:00' and
    '10-11-2012 23:59:59:59'

    David, thanks for replying.  Unfortunitly I don't know enough about SQL to put that into a query and have it return data.  Would you be able to give an example on what the query would look like?

  • Help: APEX - PL/SQL Function

    Hello,
    i need some help with a SQL statement.
    I have the follwing Table "TABF":
    ID Number,
    B_Number varchar2(10),
    G_Type varchar2(10),
    Site varchar2(50),
    Event varchar2(50),
    Date varchar(10),
    Dataset varchar2(50),
    Mode varchar2(50),
    Topic varchar2(10),
    Parameter varchar2(10),
    Value varchar2(10)The table is filled with records which, like this:
    B Number | G-Type |Site       |Event  |Date     | Dataset   | Mode    | Topic    | Parameter | Value
    800257   |   4.2  |  USA      | Test  |18.08.08 | Pre       |MBA      | Field    | F_C       | 73,9015 
    800257   |   4.2  |  USA      | Test  |03.04.96 | BL        |MBA      | Field    | F_C       | 73,6951 
    800257   |   4.2  |  USA      | Test  |03.04.96 | BL        |MBA      | Field    | F_C       | 73,71 
    800257   |   4.2  |  USA      | Test  |18.08.08 | Post      |MBA      | Field    | F_C       | 73,7526 
    800257   |   4.2  |  USA      | Test  |18.08.08 | Pre       |MBA      | Field    | F_C       | 4,5170 
    800257   |   4.2  |  USA      | Test  |03.04.96 | BL        |MBA      | Field    | F_H       | 24,6074 
    800257   |   4.2  |  England  | Test  |03.04.96 | BL        |MBA      | Field    | F_H       | 24,62 
    800257   |   4.2  |  England  | Test  |18.08.08 | Post      |MBA      | Field    | F_H       | 24,4717  Now im looking for a SELECT statement or better a function that returns a SELECT under the following condition:
    If B_Number and Event and Date and Dataset are equal, then add 3 additional columns (Topic2, Paramter2, Value2) at the first aquivalent entry.
    Then the row can be delete/ignored. If there will be another record where B_Number,Event, Date are equal to a row above then Topic3, Paramter3 and Value 3 should be added as a new column at the first record where the conditions equals.
    And so on.....
    The result should look like this for the example above:
    B Number | G-Type |  Site     |Event  |Date     | Dataset   | Mode    | Topic    |Parameter   | Value    | Topic2   |  Parameter2  | Value2
    800257   |    4.2 |  USA      | Test  |18.08.08 | Pre       | MBA     | Field    | F_C        | 73,9015  | -        | -            | -
    800257   |    4.2 |  USA      | Test  |03.04.96 | BL        | MBA     | Field    | F_C        | 73,6951  | Field    | F_H          | 24,6074
    800257   |    4.2 |  USA      | Test  |03.04.96 | BL        | MBA     | Field    | F_C        | 73,71    | Field    | F_H          | 24,62 
    800257   |    4.2 |  USA      | Test  |18.08.08 | Post      | MBA     | Field    | F_C        | 73,7526  | -        | -            | -
    800257   |    4.2 |  USA      | Test  |18.08.08 | Pre       | MBA     | Field    | F_C        | 4,5170   | -        | -            | -
    800257   |    4.2 |  England  | Test  |18.08.08 | Post      | MBA     | Field    | F_H        | 24,4717  | -        | -            | -Hope you understand my problem and some1 can help me.
    Thank you
    Regards
    Chris
    Edited by: user11369135 on 09.07.2009 00:50

    user11369135 wrote:
    Hello,
    i need some help with a SQL statement.
    I have the follwing Table "TABF":
    Now im looking for a SELECT statement or better a function that returns a SELECT under the following condition:
    If B_Number and Event and Date and Dataset are equal, then add 3 additional columns (Topic2, Paramter2, Value2) at the first aquivalent entry.
    Then the row can be delete/ignored. If there will be another record where B_Number,Event, Date are equal to a row above then Topic3, Paramter3 and Value 3 should be added as a new column at the first record where the conditions equals.
    And so on.....
    Edited by: user11369135 on 09.07.2009 00:50if I understand correctly then you want a simple GROUP BY on B_number, Event, Date and Dataset.
    But you want additionaly show 3 columns from one of the rows that was grouped.
    This can be done using the little known KEEP syntax.
    Documentation: http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions056.htm#sthref1389
    Example from the docs
    Aggregate Example
    The following example returns, within each department of the sample table hr.employees, the minimum salary among the employees who make the lowest commission and the maximum salary among the employees who make the highest commission:
    SELECT department_id,
    MIN(salary) KEEP (DENSE_RANK FIRST ORDER BY commission_pct) "Worst",
    MAX(salary) KEEP (DENSE_RANK LAST ORDER BY commission_pct) "Best"
       FROM employees
       GROUP BY department_id;
    DEPARTMENT_ID      Worst       Best
               10       4400       4400
               20       6000      13000
               30       2500      11000
               40       6500       6500
               50       2100       8200
               60       4200       9000
               70      10000      10000
               80       6100      14000
               90      17000      24000
              100       6900      12000
              110       8300      12000
                        7000       7000

  • Help on java.sql.Types class

    Hai Friends ,
    I want some help on java.sql.Types class .
    What is the use of the above class ?
    Some details about this class.

    Good Morning Yekesa
    First of all i would like to thank U for looking into my problem.
    I am using java.sql.Types.OTHER for
    {"?=CALL(storedprocedurename.functionname(?))"}
    registerOutParameter(1,javal.sql.Types.OTHER)
    setString(2,"user")
    here the
    second parameter passes an argument to function name ( viz. username say "user")
    and the function will return the ref cursor as follows:
    // declaration in pl/sql procedure
    begin
    rc ref cursor
    open rc for select * from ss_user where login_name="user";
    return rc;
    end
    now the stored procedure has a return value (i.e. stored function) which it needs to register as
    registerOutParameter(1,javal.sql.Types.OTHER)
    and it finally results in the following errors :
    Loading driver
    Before conn stmt
    After conn stmt
    Calling Stored procedure
    Stored procedure called
    java.sql.SQLException: Invalid column type
    at oracle.jdbc.dbaccess.DBError.check_error(DBError.java:243)
    at oracle.jdbc.driver.OracleStatement.get_internal_type(OracleStatement.java:2487)
    at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:64)
    at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:54)
    at sptest.<init>(sptest.java:28)
    at sptest.main(sptest.java:49)
    T couldn't understand why it is saying Invalid Column Type because its working fine with both
    java.sql.Types.INTEGER
    and
    java.sql.Types.VARCHAR
    Pl help me at the earliest as i have wasted a lot of time on it.
    pl mail me in detail at [email protected]
    bye then
    bansi
    null

  • Help in designing SQL

    Hi All,
    I need little help in designing SQL. My input and output data is given below:
    Input
    Key
    Date_1
    Date_2
    Key1
    2/14/2011 5:22:35 PM
    2/22/2011 3:05:13 PM
    Key1
    2/24/2011 1:48:07 PM
    5/24/2011 4:50:16 PM
    Key1
    2/24/2011 1:48:59 PM
    4/25/2011 3:36:19 PM
    Key1
    5/24/2011 5:18:19 PM
    6/16/2011 3:17:40 PM
    Key1
    6/16/2011 3:25:42 PM
    6/24/2011 1:33:13 PM
    Key1
    6/17/2011 1:12:54 PM
    6/25/2011 5:55:55 PM
    Output
    Key
    Date_1
    Date_2
    Key1
    2/14/2011 5:22:35 PM
    2/22/2011 3:05:13 PM
    Key1
    2/24/2011 1:48:07 PM
    5/24/2011 4:50:16 PM
    Key1
    5/24/2011 5:18:19 PM
    6/16/2011 3:17:40 PM
    Key1
    6/16/2011 3:25:42 PM
    6/25/2011 5:55:55 PM
    Here out of 2nd and third record of input, output is 2nd record of output and 5th and 6th record of input would come out as  4th record of output. Basically, if we overlapping duration between Date_1 and Date_2, we need to take min of Date_1 and max of Date_2 for that overlapping records. In case of no overlapping, we would simply output input record like  record 1 and 4 of input.
    Out of
    Key1
    2/24/2011 1:48:07 PM
    5/24/2011 4:50:16 PM
    Key1
    2/24/2011 1:48:59 PM
    4/25/2011 3:36:19 PM
    2/24/2011 1:48:07 PM was  min of above 2 and 5/24/20114:50:16 was max of above 2.
    Similarly in other overlapping scenario:
    Key1
    6/16/2011 3:25:42 PM
    6/24/2011 1:33:13 PM
    Key1
    6/17/2011 1:12:54 PM
    6/25/2011 5:55:55 PM
    6/16/2011 3:25:42 PM  was min of above 2 and 6/25/2011 5:55:55 PM was max of above 2.
    Pls help.
    Thanks.

    Hi Frank.,
    The above logic with NVL is not working.
    My input sample is:
    Key
    Date_1
    Date_2
    Key1
    2/14/2011 5:22:35 PM
    2/22/2011 3:05:13 PM
    Key1
    2/24/2011 1:48:07 PM
    5/24/2011 4:50:16 PM
    Key1
    2/24/2011 1:48:59 PM
    Key1
    5/24/2011 5:18:19 PM
    6/16/2011 3:17:40 PM
    Key1
    6/16/2011 3:25:42 PM
    6/24/2011 1:33:13 PM
    Key1
    6/17/2011 1:12:54 PM
    6/25/2011 5:55:55 PM
    I am giving create and insert statement below for creation of above data. Please see if you can help me:
    CREATE TABLE test1
      KEY1          NUMBER     ,   
      DATE_1               DATE ,          
      date_2              DATE
    insert into test1
    values(1, TO_TIMESTAMP ('2/14/2011 5:22:35 PM', 'MM/DD/YYYY HH:MI:SS AM'),TO_TIMESTAMP ('2/22/2011 3:05:13 PM', 'MM/DD/YYYY HH:MI:SS AM')  ) ;
    values(1, TO_TIMESTAMP ('2/24/2011 1:48:07 PM', 'MM/DD/YYYY HH:MI:SS AM'),TO_TIMESTAMP ('5/24/2011 4:50:16 PM', 'MM/DD/YYYY HH:MI:SS AM')  ) ;
    values(1, TO_TIMESTAMP ('2/24/2011 1:48:59 PM', 'MM/DD/YYYY HH:MI:SS AM'), '' ) ;
    values(1, TO_TIMESTAMP ('5/24/2011 5:18:19 PM', 'MM/DD/YYYY HH:MI:SS AM'),TO_TIMESTAMP ('6/16/2011 3:17:40 PM', 'MM/DD/YYYY HH:MI:SS AM')  ) ;
    values(1, TO_TIMESTAMP ('6/16/2011 3:25:42 PM', 'MM/DD/YYYY HH:MI:SS AM'),TO_TIMESTAMP ('6/24/2011 1:33:13 PM', 'MM/DD/YYYY HH:MI:SS AM')  ) ;
    values(1, TO_TIMESTAMP ('6/17/2011 1:12:54 PM', 'MM/DD/YYYY HH:MI:SS AM'),TO_TIMESTAMP ('6/25/2011 5:55:55 PM', 'MM/DD/YYYY HH:MI:SS AM')  ) ;
    commit;
    Expected output would be:
    Output
    Key
    Date_1
    Date_2
    Key1
    2/14/2011 5:22:35 PM
    2/22/2011 3:05:13 PM
    Key1
    2/24/2011 1:48:07 PM
    Key1
    5/24/2011 5:18:19 PM
    6/16/2011 3:17:40 PM
    Key1
    6/16/2011 3:25:42 PM
    6/25/2011 5:55:55 PM
    Thanks....

  • Help need in sql

    i have a scenario like
    bank_division sum(amount) total_percentage(calculated by : / total sum of adjacent amounts i.e(10000+2000+3000+4000) *100
    aaaa 10000
    bbb 2000
    ccc 3000
    dddd 40000
    for above thing i have written sql like
    select bank_division,sum(amount)  from bank group by bank;
    but i am unable to calculate percentage for each bank_division..........
    .its like for aaaa correspoding percentage will be
    10000/ total sum of adjacent amounts i.e(10000+2000+3000+4000) *100
    and for bbb it will be
    2000/ total sum of adjacent amounts i.e(10000+2000+3000+4000) *100
    so on...
    can any one help me how to write in single sql

    user632733 wrote:
    in your sql you are using lag to display from existing total_sal....which cant be possible in above scenario..??? Where did you see existing total_sal? EMP table:
    SQL> select deptno,ename,sal from emp
      2  /
        DEPTNO ENAME             SAL
            20 SMITH             800
            30 ALLEN            1600
            30 WARD             1250
            20 JONES            2975
            30 MARTIN           1250
            30 BLAKE            2850
            10 CLARK            2450
            20 SCOTT            3000
            10 KING             5000
            30 TURNER           1500
            20 ADAMS            1100
        DEPTNO ENAME             SAL
            30 JAMES             950
            20 FORD             3000
            10 MILLER           1300
    14 rows selected.
    SQL> As you can see, there are multiple employees in each department. Now look at mu solution. Inner select:
             select  deptno,
                     sum(sal) total_sal
               from  emp
               group by deptnosummarizes sal for each department. If you run it separately:
    SQL>          select  deptno,
      2                   sum(sal) total_sal
      3             from  emp
      4             group by deptno
      5  /
        DEPTNO  TOTAL_SAL
            30       9400
            20      10875
            10       8750
    SQL> Outer select calculates previous department total salary and its ratio to report.
    SY.
    P.S. And if you want to display individual employees along with department level summarization:
    select  deptno,
            ename,
            total_sal,
            prev_deptno,
            last_value(total_sal) over(order by deptno range between unbounded preceding and 1 preceding) prev_dept_total_sal,
            ratio_to_report(total_sal) over () * 100
      from  (
             select  deptno,
                     ename,
                     sum(sal) over(partition by deptno) total_sal,
                     max(deptno) over(order by deptno range between unbounded preceding and 1 preceding) prev_deptno
               from  emp
      order by deptno
        DEPTNO ENAME       TOTAL_SAL PREV_DEPTNO PREV_DEPT_TOTAL_SAL RATIO_TO_REPORT(TOTAL_SAL)OVER()*100
            10 MILLER           8750                                                           6.38569604
            10 KING             8750                                                           6.38569604
            10 CLARK            8750                                                           6.38569604
            20 ADAMS           10875          10                8750                           7.93650794
            20 FORD            10875          10                8750                           7.93650794
            20 JONES           10875          10                8750                           7.93650794
            20 SMITH           10875          10                8750                           7.93650794
            20 SCOTT           10875          10                8750                           7.93650794
            30 WARD             9400          20               10875                           6.86006203
            30 TURNER           9400          20               10875                           6.86006203
            30 ALLEN            9400          20               10875                           6.86006203
        DEPTNO ENAME       TOTAL_SAL PREV_DEPTNO PREV_DEPT_TOTAL_SAL RATIO_TO_REPORT(TOTAL_SAL)OVER()*100
            30 JAMES            9400          20               10875                           6.86006203
            30 BLAKE            9400          20               10875                           6.86006203
            30 MARTIN           9400          20               10875                           6.86006203
    14 rows selected.
    SQL>

  • I need help, CFquery and SQL NOT BETWEEN

    OK I am building a hotel booking system as a college project and I'm having trouble with finding rooms that are available. Now I have got this working, to an extent, So to give you the bigger picture al try and lay this out the best I can so you can understand.
    This is my database structure:
    Bookings Table
    Rooms Table
    Customers Table
    BookingID
    BookingDateIN
    BookingDateOUT
    RoomID
    CustomerID
    RoomID
    RoomType
    RoomNumber
    RoomPrice
    Room Description
    CustomerID
    FullName
    AddressLine1
    AddressLine2
    PostalCode
    CarReg
    OK, now you can see how this is going to work with the Bookings Tables RoomID and CustomerID matching the others to make a relationship, simple databasing.
    Now I have a page that lets you select a date and then select how many days the customer wants to stay for. So the selected date will be put towards the BookingDateIN field and the calculated date will be put towards the BookingDateOUT in a NOT BETWEEN SQL statement.
    I have got this to work with some test data, how ever when I select a date range that is below the 5th day in any month it shows the rooms are booked and not available even though the test data does not contain any days below the 5th.
    This is my test data in the Bookings Table:
    BookingID
    BookingDateIN
    BookingDateOUT
    CustomerID
    RoomID
    1
    20/05/2010
    23/05/2010
    2
    2
    2
    26/05/2010
    28/05/2010
    1
    5
    And here is my code for the bookings page:
    <cfset CurrentPage=GetFileFromPath(GetBaseTemplatePath())>
    <cfif isDefined("FORM.SearchRooms")>
    <!-- adds the number of days to the selected date -->
    <cfset #CalDate# = #DateFormat( DateAdd( 'd', #FORM.SelDays#, #FORM.SelDate# ), 'dd/mm/yyyy' )#>
    <!-- Queries the Bookings table with a crazy NOT BETWEEN SQL Statement -->
    <cfquery name="Check_Rooms_RS" datasource="HotelBookingSystem" username="HBSuser" password="HBSpass">
        SELECT *
        FROM Bookings
        WHERE BookingDateIN AND
        BookingDateOUT NOT BETWEEN
        <cfqueryparam value="#FORM.SelDate#" cfsqltype="cf_sql_timestamp">
        AND
        <cfqueryparam value="#CalDate#" cfsqltype="cf_sql_timestamp">
    </cfquery>
    <!-- Now this is my beginner CFQuery'n lol it queries the Rooms table with the values output from the bookings query and loops, then I put a 0 at the end to have the correct SQL statement lol I'm trying -->
    <cfquery name="Rooms_RS" datasource="HotelBookingSystem" username="HBSuser" password="HBSpass">
    SELECT *
    FROM Rooms
    WHERE RoomID = <cfloop query="Check_Rooms_RS">#RoomID# OR </cfloop>0
    </cfquery>
    </cfif>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Hotel Booking System - User Manager</title>
    <link rel="stylesheet" type="text/css" href="../style.css"/>
    </head>
    <body>
    <div class="container">
        <div class="booking_choose_date">
             <cfparam name="PreSelDate" default="#LSDateFormat(Now(), 'dd/mm/yyyy')#">
    <cfif isDefined("FORM.SearchRooms")>
        <cfset #PreSelDate# = #FORM.SelDate#>
    </cfif>
            <cfform name="form1" width="375" height="350" action="#currentpage#">
    <!-- Date Picker -->
               <cfinput type="DateField" name="SelDate" label="Block out starts" width="100" value="#PreSelDate#" mask="DD/MM/YYYY">
    <!-- Day Picker -->
    <cfselect size="1" name="SelDays" required="Yes" message="Select days staying">
          <option value="1" selected>1 Day</option>
          <option value="2">2 Days</option>
          <option value="3">3 Days</option>
          <option value="4">4 Days</option>
          <option value="5">5 Days</option>
          <option value="6">6 Days</option>
          <option value="7">7 Days</option>
    </cfselect>
               <cfinput type="Submit" name="SearchRooms" value="Check" width="100">
            </cfform>
        </div>
         <cfif isDefined("FORM.SearchRooms")>
            <div class="search_results">
              <!-- Outputs the Bookings table RoomID values -->
                <cfoutput query="Check_Rooms_RS">
                     #Check_Rooms_RS.RoomID#
                </cfoutput>
              <!-- Outputs the Rooms table RoomID values -->
                <cfoutput query="Rooms_RS">
                     #Rooms_RS.RoomType#
                </cfoutput>  
            </div>
        </cfif>
    </div>
    </body>
    </html>
    Little help with this would be amazing !!

    I only skimmed this thread. But even ignoring the myriad of date issues, the queries have a serious "logic" problem.  If you think about it, does searching for rooms that are not reserved in a table that only contains reserved rooms really make sense? Say you have twenty (20) rooms.  If only two (2) of them are reserved (ie in the Bookings table), how is that first query supposed to account for the other eighteen (18)?
    It would make more sense to search the Bookings table for rooms that are reserved.  Then query your Rooms table for rooms not in that list (ie available).  Granted that is not a very efficient method for a real application. But should work for your purposes.
    This is my test data in the Bookings Table:
    Are you storing the booking dates as strings?  Dates should be stored in a date/time column.  Storing them as strings creates all kinds of problems. Not to mention it makes it more difficult to use your database's date functions.

  • Help needed for SQL query

    hello ,
    I am a beginner in terms of writing sql queries. I hope some body can help me out.
    I have two tables
    mysql> desc user_group_t;
    ---------------------------------------------------+
    | Field | Type | Null | Key | Default | Extra |
    ---------------------------------------------------+
    | userAccountId | char(8) | | PRI | | |
    | groupId | char(8) | | PRI | | |
    ---------------------------------------------------+
    2 rows in set (0.00 sec)
    mysql> desc group_t;
    ---------------------------------------------------+
    | Field | Type | Null | Key | Default | Extra |
    ---------------------------------------------------+
    | id | char(8) | | PRI | | |
    | name | char(50) | YES | | NULL | |
    | email | char(100) | YES | | NULL | |
    | description | char(254) | YES | | NULL | |
    | parentId | char(8) | YES | | NULL | |
    | creatorId | char(8) | YES | | NULL | |
    | createDate | char(20) | YES | | NULL | |
    | updateDate | char(20) | YES | | NULL | |
    | updatorId | char(8) | YES | | NULL | |
    ---------------------------------------------------+
    9 rows in set (0.00 sec)
    what I want is list of all groups with id,name and #of members(which is the # of rows in the user_group_t for any given id). Importantly I need the groups with 0 members also to be listed. In short my output should contain exactly the same number of rows as in group_t table with an additional column indicating # of members for that group.
    Any help would be greatly appreciated.
    Thanks in Advance.
    -Vasanth

    Thanks Donald,
    Actually I figured it out, with the following query:
    select id,name,sum(if(groupid is not null,1,0)) as members from group_t left join user_group_t on id=groupid group by id;
    I tried your solution, but mysql says there is an error at '+' . Anyway I modified your solution to the one below and it worked.
    select a.id, a.name, count(b.groupid) from group_t a left join user_group_t b on a.id=b.groupid group by a.id, a.name;
    I tried that before but then I used Count(*) instead of count on groupid. Your solution is elagant and I will go with yours.
    Thanks again.
    Vasanth

  • *URGENT HELP REQUIRED* java.sql.SQLException: Invalid Oracle URL specifed

    Hi all,
    In the middle of the last week for my final year project and having to convert to an Oracle database due to compatibility problems with university Tomcat Server and MS Access. I'm having trouble connecting to the Oracle database and would appreciate some help please.
    Running on Windows 98 in the lab here, and the Oracle 9i, release 9.2.0.2.0, J2SDK1.4.0, Classes12.zip installed OK.
    Code for connection looks like this inside the constructor of my class:
    Class.forName("oracle.jdbc.driver.OracleDriver");
    cardSaleConnexion = DriverManager.getConnection("jdbc:oracle:[email protected]:1521:sid","user_name","pwdt");
    System.out.println("Connection Successful ");
    And I'm getting the following error when calling the constructor in a driver program:
    java.sql.SQLException: Invalid Oracle URL specified
         at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
         at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
         at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:269)
         at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:188)
         at java.sql.DriverManager.getConnection(DriverManager.java:512)
         at java.sql.DriverManager.getConnection(DriverManager.java:171)
         at CardSale.<init>(CardSale.java:30)
         at Driver.main(Driver.java:11)
    Exception in thread "main"
    Please reply on a very urgent basis.
    Kind regards,
    Peter

    Try ojdbc14.jar as the JDBC driver instead of classes12.zip.
    Refer:
    http://otn.oracle.com/software/tech/java/sqlj_jdbc/htdocs/jdbc9201.html
    http://docs.sun.com/source/817-5603-10/index.html
    Database Driver
    This section describes the known database driver issues and associated solutions.
    ID      Summary
    4700531      On Solaris, an ORACLE JDBC driver error occurs.
         This new Java Database Connectivity (JDBC) driver is for Oracle (R) working with JDK1.4. The problem is caused by a combination of the Oracle 9.1 database and ojdbc14.jar. Applying the patch will fix the problem on Solaris 32-bit machine, running an Oracle 9.0.1.3 database.
         Solution
         Obtain and apply the patch to your server from the Oracle Web site for Bug 2199718. Perform the following steps:
         1.��Go to the Oracle web site.
         2.��Click the 'patches' button.
         3.��Type 2199718 in the patch number field.
         4.��Click the 32-bit Solaris OS patch.Go to Metalink.oracle.com.
         5.��Click patches.
         6.��Under patch number, enter 2199718.
         7.��Click the 32 bit Solaris OS patch.
    4707531      On Solaris, accessing an Oracle 9.1 database with an Oracle 9.2 Client may cause data corruption.
         If you use an Oracle (R) 9.2 client to access an Oracle 9.1 database, data corruption might occur when a number column follows a timestamp column.
         The problem might be caused by using the ojdbc14.jar file with an Oracle 9.1 database. Applying the patch might assist in addressing the situation on Solaris 32-bit machines, running an Oracle 9.1 database. This JDBC driver is for Oracle working with JDK1.4.
         Solution
         Obtain the patch that Oracle might make available from the Oracle web site for Bug 2199718 and apply it to your server.
    Regards,
    Pankaj D.

  • Need help in using SQL in a jsp file to compare date and time

    hi every one,
    Actually I am doing a project using JSP. I need to compare a date field in the database (MS Acess) to the current system date and time. I have to do this in a select statement.
    I have alredy defined a variable of type Date in the JSP file and I am comparing this variable to the date in the database through a select statemant.
    Here is what I am doing
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
              java.util.Date today = new java.util.Date();
              String myDate=sdf.format(today);
    query = "SELECT Car_ID, Model_ID, Year, Ext_Color, Price from Cars where EDate <= "+myDate+" ;";
    EDate is the feild in the database and it's format is (5/12/2008 5:29:47 PM) it is of type Date/Time in MS Acess.
    when I execute the query it gives the following error
    SQL error:java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression 'EDate <= 2008-10-16 08:10:07'.
    I hope any one can help me with that error and answer my question, I've tried too many things but nothing helps
    Thanks in advance :-)

    Hi,
    When the comparision is needed to be done with the current date , we don't need to send in Java
    Date then format it and compare with MS Acess Date.
    In MS Access we have Date() function which will give you the current date.
    So you can try rewriting your query as following :
    query = "SELECT Car_ID, Model_ID, Year, Ext_Color, Price from Cars where EDate <= Date() ;"; ---------------------
    Hope this helps.
    Thanks

  • Please help with an sql to show more than one records into single row for each student

    From the following data I would like to create an sql to get the information  as the following layout
    studentid,  firstTerm,  EnglishMark1,ScienceMark1,MathsMark1, Secondterm,EnglishMark2,ScienceMark2,MathsMark2,
    ThirdTerm,EnglishMark3,ScienceMark3,MathsMark3 // As single rows for each student
    Example
    1 First, 30,40,20,Sec,30,40,20,  simillarly next row for next row for another sudent. Please help to generate the sql for the same.
    Please help it would be very appreciate.
    With Thanks
    Pol
    polachan

    create table yourdata (studentid int, term varchar(10), section varchar(50), Mark int)
    insert into yourdata values
    (1,'First','Math',20),(1,'First','English',30),(1,'First','Science',40),
    (2,'First','Math',20),(2,'First','English',30),(2,'First','Science',40),
    (3,'First','Math',20),(3,'First','English',30),(3,'First','Science',40),
    (1,'Sec','Math',20),(1,'Sec','English',30),(1,'Sec','Science',40),
    (2,'Sec','Math',20),(2,'Sec','English',30),(2,'Sec','Science',40),
    (3,'Sec','Math',20),(3,'Sec','English',30),(3,'Sec','Science',40)
    Select studentid
    ,max(case when term='First' and section='English' Then Mark End) as EnglishMark1
    ,max(case when term='First' and section='Science' Then Mark End) as ScienceMark1
    ,max(case when term='First' and section='Math' Then Mark End) as MathMark1
    ,max(case when term='Sec' and section='English' Then Mark End) as EnglishMark2
    ,max(case when term='Sec' and section='Science' Then Mark End) as ScienceMark2
    ,max(case when term='Sec' and section='Math' Then Mark End) as MathMark2
    ,max(case when term='Third' and section='English' Then Mark End) as EnglishMark3
    ,max(case when term='Third' and section='Science' Then Mark End) as ScienceMark3
    ,max(case when term='Third' and section='Math' Then Mark End) as MathMark3
    From yourdata
    Group by studentid
    drop table yourdata

  • Need help on Dynamic SQL Cursor in Forms

    Hi All,
    I am trying to execute Dynamic SQL Cursor in forms using EXEC_SQL built in.
    I have a cursor for example:
    'select * from supplier where supplier = '||p_supplier||' and processing_order = '||p_order
    My code is
    cur_num := Exec_SQL.Open_cursor;
    sql_order := 'select * from supplier where supplier = '||p_supplier||' and processing_order = '||p_order;
    EXEC_SQL.PARSE(cursor_number, sql_order);
      EXEC_SQL.DEFINE_COLUMN(cur_num ,1,ln_Supp_Id);
      EXEC_SQL.DEFINE_COLUMN(cur_num ,2,ls_Suppl_Name,30);
    EXEC_SQL.DEFINE_COLUMN(cur_num ,24,ls_exchange,20);
      sql_count := EXEC_SQL.EXECUTE(cur_num );
      While EXEC_SQL.FETCH_ROWS(cur_num ) > 0 Loop
            EXEC_SQL.COLUMN_VALUE(cur_num ,1,ln_Supp_Id);
            EXEC_SQL.COLUMN_VALUE(cur_num ,2,ls_Suppl_Name);
            EXEC_SQL.COLUMN_VALUE(cur_num ,24,ls_exchange);
    End Loop;
    EXEC_SQL.CLOSE_CURSOR(cur_num );
    In this case I have to write 24 Define Columns and 24 Column value. Is there any way to assign them to %rowtype at one time as I need all coulmn of the table.
    I had similar case on multiple tables.
    Please help me
    Thanks,
    Maddy

    I need this dynamic sql because p_supplier and p_order values changes at run time
    I do not understand. Is this a simplified sample or the real thing? You do know that you can pass variables to cursors:
    cursor test is
    select * from supplier where supplier = p_supplier and processing_order = p_order;
    or does e.g. p_supplier hold other parts of the query?
    cheers

  • Help Needed In SQL Query

    HI All,
    Oracle sql clarification required
    Sample Table:
    empno empname Job mgr_id hire_date salary deptno
    7788 SCOTT ANALYST 7566 19-APR-87 3000 20
    7902 FORD ANALYST 7566 03-DEC-81 3000 20
    7934 MILLER CLERK 7782 23-JAN-82 1300 10
    7900 JAMES CLERK 7698 03-DEC-81 950 30
    7369 SMITH CLERK 7902 17-DEC-80 800 20
    7876 ADAMS CLERK 7788 23-MAY-87 1100 20
    Need "single / one" sql for this requirement statement:
    There will be 2 drop down boxes (1st - Job list, 2nd - empno) in the form in which the following result set is expected
    1) When user selects value from 1st drop down box (job) as "ANALYST" leaving the second drop down unselected, the result expected is 2 (no. of rows for that job)
    2) When user selects value from 1st drop down box (job) as "ANALYST" and the value from 2nd drop down box as 7902, the result expected is 1 (no of rows for that job and empno)
    Sqls which I have tried from my side (given below) didn't give the expected result and please do help me in correcting this
    select count(1) from scott.emp where job='ANALYST' and ( empno = :empno or empno is null ) ;
    Please help for this requirement. Any help is deeply appreciated.
    Thanks
    Zaheer

    Hi,
    welcome to the forum.
    Please read SQL and PL/SQL FAQ
    When you put some code or output please enclose it between two lines starting with {noformat}{noformat}
    i.e.:
    {noformat}{noformat}
    SELECT ...
    {noformat}{noformat}
    For your question the following will both work:SQL> select * from emp
    where job='ANALYST' and (empno =:empno or :empno is null)
    EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
    7788 SCOTT ANALYST 7566 19/04/1987 00:00:00 3000 20
    7902 FORD ANALYST 7566 03/12/1981 00:00:00 3000 20
    2 rows selected.
    SQL> select * from emp
    where job='ANALYST' and empno =NVL(:empno, empno)
    EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
    7788 SCOTT ANALYST 7566 19/04/1987 00:00:00 3000 20
    7902 FORD ANALYST 7566 03/12/1981 00:00:00 3000 20
    2 rows selected.
    Regards.
    Al                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Maybe you are looking for