SELECT from two tables

Hello, I have a problem writing a specific SELECT statement and I hope you'll help me out.
I have two tables:
Clients:
- ID integer (PK)
- Name_SecondName varchar(20)
- Gender char
- Balance integer
Investments:
- ID integer (PK)
- Amount integer
- Interest Numeric(3,2)
- Client_ID (FK)
My job is to display a number of men and a number of women who have at least one investment higher than $1000. I'll skip adding the data to the table, my point is just to find a proper construction for the SQL query. Right now I've got this:
SELECT COUNT(DISTINCT Client_ID), COUNT(DISTINCT Client_ID)
FROM Clients JOIN Investments
ON Clients.ID = Investments.Client_ID
WHERE Amount > 1000;
Obviously it twice displays the number of clients with an investment higher than $1000. But how do I specify that the first COUNT counts men (Gender='M') and second - women (Gender = 'F') ?? Can anyone help me?
Edited by: 934019 on 2012-05-13 12:10

I'm using Oracle Database 11g Express Edition Release 11.2.0.2.0 - Production
Here's the code:
CREATE TABLE Clients
Client_ID INTEGER PRIMARY KEY,
Name_SecondName VARCHAR(20),
Gender CHAR,
Balance INTEGER
CREATE TABLE Investments
Investment_ID INTEGER PRIMARY KEY,
Amount INTEGER,
Interest NUMERIC(3,2),
Client_ID INTEGER REFERENCES Clients(Client_ID)
INSERT INTO Clients VALUES (1, 'Brad_Pitt', 'M', 100000);
INSERT INTO Clients VALUES (2, 'Angelina_Jolie', 'F', 200000);
INSERT INTO Clients VALUES (3, 'George_Clooney', 'M', 250000);
INSERT INTO Clients VALUES (4, 'Meryl_Streep', 'F', 150000);
INSERT INTO Clients VALUES (5, 'Colin_Farrell', 'M', 200000);
INSERT INTO Clients VALUES (6, 'Scarlett_Johansson', 'F', 400000);
INSERT INTO Investments VALUES (1, 10000, 4.25, 4);
INSERT INTO Investments VALUES (2, 20000, 4.65, 3);
INSERT INTO Investments VALUES (3, 15000, 3.85, 2);
INSERT INTO Investments VALUES (4, 30000, 4.85, 6);
INSERT INTO Investments VALUES (5, 25000, 4.5, 3);
INSERT INTO Investments VALUES (6, 15000, 4.35, 5);
INSERT INTO Investments VALUES (7, 20000, 4.75, 6);
INSERT INTO Investments VALUES (8, 10000, 4.15, 1);
INSERT INTO Investments VALUES (9, 25000, 4.6, 3);
INSERT INTO Investments VALUES (10, 20000, 4.15, 4);
And now I make a SELECT statement as follows:
SELECT COUNT(DISTINCT Client_ID), COUNT(DISTINCT Client_ID)
FROM Clients NATURAL JOIN Investments
WHERE Investments. Amount > 15000;
The result is:
COUNT (DISTINCT Client_ID) *3*
COUNT(DISTINCT Client_ID) *3*
It now displays '3' because there are 3 clients who have at least one investment higher than 15000 (George Clooney, Meryl Streep and Scarlett Johansson).
So again the question is how to make the first COUNT count only men and the second COUNT - only women? I don't want it to display the clients - just the number of them.

Similar Messages

  • Select from two tables and insert into a third

    I'm trying to do a select from two tables and do an insert into a third table from the two resulting columns.
    I have the following....
    DECLARE
    tempsid number;
    temphostid number;
    BEGIN
    select "DBSID_ID","ID" into tempsid,temphostid from "DBSIDS","SERVERS"
    where "HOST_SID" like '%'||"DBSID_NAME"||'%'
    and "HOST_NAME" not like 'vio%'
    and exists (select "DBSID_NAME" from DBSIDS)
    order by "DBSID_NAME";
    insert into "DBSID_LOOKUP" ("SIDLOOKUP_ID", "SERVERLOOKUP_ID")
    values(tempsid, temphostsid);
    END;
    run;
    I get the error ....
    ORA-06550: line 11, column 18:
    PL/SQL: ORA-00984: column not allowed here
    ORA-06550: line 10, column 1:
    PL/SQL: SQL Statement ignored
    1. DECLARE
    2. tempsid number;
    3. temphostid number;

    okay ... I tried a different way ...
    DECLARE
    a number;
    b number;
    BEGIN
    select "DBSID_ID","ID" into a,b from "DBSIDS","SERVERS"
    where "HOST_SID" like '%'||"DBSID_NAME"||'%'
    and "HOST_NAME" not like 'vio%'
    and exists (select "DBSID_NAME" from DBSIDS)
    order by "DBSID_NAME";
    insert into "DBSID_LOOKUP" (SIDLOOKUP_ID, SERVERLOOKUP_ID) values (a, b);
    END;
    and now it whines about ...
    ORA-01422: exact fetch returns more than requested number of rows

  • Selecting from two tables and confirming from them despites they not relate

    Please I need a query to select from two tables that are not related to each other.
    I also want to confirm data's as in verify wether what the user has entered is in accordance with what is in the tables
    Examples
    the first table is named "Card" and the second table is named "Student_Details"
    Card table contains a column named "Pin_Number".
    The Student_Details table contains fields such as Exam_Number, Name, Age, Sex.
    The user has to Enter the Pin_Number which has to be confirmed in the Card table and Exam_Number which has to be confirmed in the Student_Details table and verify that both data's are correct.
    Please I need the SQL and PL/SQL queries for this problem.
    Thanks

    Hi,
    I think you need two different queries
    You can write a procedure like:
    create or replace procedure p1 (p_pin_number number, p_exam_number)
    is
      r_card_row            card%rowtype;
      r_student_details     student_details%rowtype;
      cursor c1 is
      select *
        from card
       where pin_number = p_pin_number;
      cursor c2 is
      select *
        from student_details
       where exam_number = p_exam_number;
    begin
      open c1;
        loop
          fetch c1 into  r_card_row;
          exit when c1%notfound;
          ....  do whatever you want..... and the samething you can do with other cursor
        end loop;
      close c1;
    end p1;Hope this helps
    Ghulam

  • Selecting from two tables but making it just one selection

    Is there a way to select from two tables and just have one selection appear?
    Specifically I have a fact_install_unit, and a fact_install_arch table.
    Sometimes the value exists in fact_install_unit.factory_timestamp, and sometimes when fact_install_unit.factory_timestamp is null I need to pull it from the fact_install_arch.factory_timestamp.
    sort of like:
    (select fact_install_unit.factory_timestamp
    from fact_install_unit, fact_install_arch
    where fact_install_unit.fl_unit_sak = fact_install_arch.fl_unit_sak
    and where fact_install_unit.factory_timestamp is null then display fact_install_arch.factory_timestamp)

    > I was just stating that I do not have sufficient priveleges to create views in this database.
    >
    nm means "no more" than that
    And how are we supposed to know that? You seem to have changed the thread subject to "unfortunately I only have read-only and insufficient priveleges", which is not even a question.
    nm means "New Mexico":
    http://www.myshortpencil.com/schooltalk/messages/85/515.html?971794944

  • Selecting from two tables

    I have two tables:
    TABLE: users (user_is is primary key):
    ++++++++++++++++++++++++++++++++++++++
    user_id     | username
    1     | fazle
    2     | newaz
    3     | shaerul
    4     | badsha
    5     | mirmohsin
    6     | mdmohsin
    7     | shawkat
    8     | ahsan
    9     | admin
    TABLE: key_movement_history (history_id is primary key, key_handover_user_id and     key_takeover_user_id links to users.user_id):
    ++++++++++++++++++++++++++++++++++++++++++++++++++
    history_id     | handover_date     | key_handover_user_id |     key_takeover_user_id
    1     | 2006-10-18 16:25:07     | 8               |      2
    2     | 2006-10-18 17:03:09          | 2               |      8
    3     | 2006-10-18 17:04:45     |     8               |     1
    4     | 2006-10-18 17:28:35     |     1               |      8
    5     | 2006-10-18 17:31:59          | 8               |      1
    6     | 2006-10-19 19:04:02          | 1               |     8
    What is want is:
    TABLE 3:
    ++++++++
    handover_date     | key_handover_username | key_takeover_username
    2006-10-18 16:25:07     | ahsan     | newaz
    2006-10-18 17:03:09     | newaz          | ahsan
    2006-10-18 17:04:45     | ahsan          | fazle
    2006-10-18 17:28:35     | fazle          | ahsan
    2006-10-18 17:31:59     | ahsan          | fazle
    2006-10-19 19:04:02     | fazle          | ahsan
    Could anyone please tell me the select statement?
    I tried
    SELECT key_movement_histories.handover_date, users.username, users.username FROM key_movement_histories, users WHERE users.user_id = key_movement_histories.key_handover_user_id and users.user_id = key_movement_histories.key_takeover_user_id;
    but this did not work.
    Thanks in advance.
    Message was edited by:
    user538091

    sql>select * from t1;
        USER_ID  USERNAME
        1  Fazle 
        2  Nawaz 
        3  Sherul
    sql>select * from t2;
        HISTORY_ID  DT  HO_ID  TO_ID
        1  06-oct-06  1  2 
        2  16-oct-06  2  3 
        3  26-oct-06  3  1
    sql>select t2.history_id,t2.dt,
           t11.username ho_user,t12.username to_user
        from t1 t11,t1 t12,t2
        where t11.user_id = t2.ho_id
        and t12.user_id = t2.to_id;
        HISTORY_ID  DT  HO_USE  TO_USE 
        1  06-oct-06  Fazle  Nawaz 
        2  16-oct-06  Nawaz  Sherul 
        3  26-oct-06  Sherul  Fazle 
    jeneesh

  • Selection from different tables

    Hello Everyone,
    I have a situation where I have 15 fields in the selection screen.
    The selection is dependent on three or more tables.
    First I have selected from two tables but if the user enters values in the selection screen then how to make the selection.
    Tables dont have common fields between them. LIKP, LIPS, VTTK, VBUK and VEKP are the tables.
    Can you guys guide me.
    Thank you.

    Hi Vinod,
    First I have selected from two tables but if the user enters values in the selection screen then how to make the selection.
    Your query is not so clear. When are you fetching the data from two table whether before selection screen input (Initialization event) or after selection screen?
    Can you please elaborate your query and better if you post your Selection Screen screen-shot.
    Regards,
    VIjay

  • Urgent. . .About select * from multiple tables

    When I am doing the 'Select * from tables' in JSP,
    sql = dbconn.prepareStatement("SELECT * FROM protein WHERE protein_id ='"+p_i+"'");
    It works, because I only select one table.
    Then, I change to select from two tables,
    sql = dbconn.prepareStatement("SELECT * FROM protein, fuses WHERE protein_id ='"+p_i+"'");
    It also works properly?
    However, When I do like:
    sql = dbconn.prepareStatement("SELECT * FROM protein, protein_taxa WHERE protein_id ='"+p_i+"'");
    It doesn?t work.
    So, I think it might be the problem that there is a common column 'protein_id' in both tables, although protein_taxa.protein_id is a foreign key of protein.protein_id. Therefore, I can select two table protein, fuses which have different columns, but no way to select the table they have same name column.
    However, it?s essential for me to select all the data from the database. Any way I could achieve it? Thanks a lot!!

    SELECT *
    FROM protein, protein_taxa
    WHERE protein.protein_id = 'a_protein_id'
    and protein.protein_id = protein_taxa.protein_id It would also be good to indicate which fields you want on the select clause. This will liberate the server to return two fields with the same name.
    SELECT protein.protein_id, protein.name, protein_taxa.taxa /* ??? */
    FROM protein, protein_taxa
    WHERE protein.protein_id = 'a_protein_id'
    and protein.protein_id = protein_taxa.protein_id

  • To Select the data from two table one is transp table and onther is cluster

    Hi All,
    I want to select the data from two tables
    Here i am giving with an example.
    Fileds: kunnr belnr from bseg.  table bseg
    fields: adrnr from kna1     table: kna1.
    Know i want to put these into one internal table based on kunnr and belnr.
    Thanks in advance.
    Ramesh

    Hi,
       U cant use joins on cluster table and BSEG is a cluster table so use FOR  ALL ENTRIES for taht
    refer this code
    *&      Form  sub_read_bsak
          text
    -->  p1        text
    <--  p2        text
    FORM sub_read_bsak.
    *--Select data from BSAK Table
      SELECT lifnr
             augdt
             augbl
             gjahr
             belnr
             xblnr
             blart
             dmbtr
             mwskz
             mwsts
             sgtxt
             FROM bsak
             INTO CORRESPONDING FIELDS OF TABLE it_bsak
             WHERE belnr IN s_belnr
             AND   augdt IN s_augdt.
      IF sy-subrc EQ 0.
    *--Sort table by accounting document and vendor number
        SORT it_bsak BY belnr lifnr.
      ENDIF.
    ENDFORM.                    " sub_read_bsak
    *&      Form  sub_read_bseg
          text
    -->  p1        text
    <--  p2        text
    FORM sub_read_bseg.
      IF NOT it_bsak[] IS INITIAL.
    *--Select data from BSEG table
        SELECT belnr
               gjahr
               shkzg
               kostl
               hkont
               ebeln
               ebelp
               FROM bseg
               INTO CORRESPONDING FIELDS OF TABLE it_bseg
               FOR ALL ENTRIES IN it_bsak
               WHERE belnr EQ it_bsak-belnr
               AND   gjahr EQ it_bsak-gjahr
               AND   shkzg EQ 'S'.
        IF sy-subrc EQ 0.
    *--Sort table by accounting document
          SORT it_bseg BY belnr.
        ENDIF.
      ENDIF.
    ENDFORM.                    " sub_read_bseg

  • Need of SQL query in selecting distinct values from two tables

    hi,
    I need a query for selecting distinct values from two tables with one condition.
    for eg:
    there are two tables a & b.
    in table a there are values like age,sex,name,empno and in table b valuses are such as age,salary,DOJ,empno.
    here what i need is with the help of empno as unique field,i need to select distinct values from two tables (ie) except age.
    can anybody please help me.
    Thanks in advance,
    Ratheesh

    Not sure what you mean either, but perhaps this will start a dialog:
    SELECT DISTINCT a.empno,
                    a.name,
                    a.sex,
                    b.salary,
                    b.doj
    FROM    a,
            b
    WHERE   a.empno = b.empno;Greg

  • Select data from two tables...!

    HI Experts...!
    i m a beginner user and i want to select data from two tables proj and prps.....using joins.....and internal tables i have written a code...
    SELECT prps~pspnr
           prps~objnr
           prps~psphi
           proj~ernam
           proj~erdat
           proj~pspnr
    INTO  table itab   -
    itab is internal table
    FROM prps inner join proj
    WHERE pspnr in p_no and prpspsphi = projpspnr.
    but there is error in from clause ..please help me....
    Advance thanx....

    Hi,
    check the sample code bellow above two reply will solve out your problem but one more extra line in your code pointed out bellow.
    TABLES: prps, proj.
    TYPES:  BEGIN OF ty_test,
            pspnr LIKE prps-pspnr,
            objnr LIKE prps-objnr,
            psphi LIKE prps-psphi,
            ernam LIKE proj-ernam,
            erdat LIKE proj-erdat,
            END OF ty_test.
    DATA: itab TYPE STANDARD TABLE OF ty_test WITH HEADER LINE.
    SELECT-OPTIONS: p_no FOR prps-pspnr.
    SELECT  prps~pspnr
            prps~objnr
            prps~psphi
            proj~ernam
            proj~erdat
    *        proj~pspnr " No need for this you have selected this in
    *     the first line because it is commone so you only need to select from any one
            INTO TABLE itab
    FROM prps INNER JOIN proj ON ( prps~pspnr = proj~pspnr  )
    WHERE prps~pspnr IN p_no.
    Best Regards,
    Faisal
    Edited by: Rob Burbank on Dec 24, 2009 12:24 PM

  • Selecting data from two tables

    I am trying to select data from two tables.  The only problem that I am running into, is that i am only seeing results from my 'uploads' table.  there is also a record in documents where user = 1 that should show up.  here is my sql:
    $userIDNum = 1;
    $sql="Select *
    from uploads, documents
    WHERE uploads.user = documents.user AND uploads.user = $userIDNum
    ORDER BY uploads.title ASC, documents.title ASC";

    You'll need to explain a little more about your data and what you are trying to accomplish. Your current sql will select all columns from both the uploads and documents tables but only rows where the user id in both tables match, AND the user id equals 1. Is that not what you are seeing? Where's the code that outputs the results?

  • Selecting columns from two table is slow but same

    I am selecting 27 columns from two tables
    which running for more than 30 minutes. but
    if I select count(*) with the same query
    except the columns it is coming in seconds.
    Where is the error?

    If you post
    1) The table definitions for the underlying tables
    2) The indexes that are on the tables
    3) The two SQL statements you're running
    4) The explain plan for both statements
    we can probably be of some assistance.
    My guess is that the count(*) is able to return much more quickly because the optimizer is able to use a significantly faster query plan that is based on an index which the longer-running query cannot utilize. Without the information I've requested, though, it's hard to do more than speculate.
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • How to populate a table based on a row selection from another table.

    Hi, i just started to use ADF BC and Faces. Could some one help me or point me a solution on the following scenario .
    By using a search component , a table is being displayed as a search result. If i select any row in the resulted table , i need to populate an another table at the bottom of the same page from another view. These two tables are related by primary key . May i know how to populate a table based on a row selection from another table. Thanks
    ganesh

    I understand your requirement and the tutorial doesn't talk about Association between the views so that you can create a Master-Detail or in DB parlance, a Parent-Child relationship.
    I will assume that we are dealing with two entities here: Department and Employees where a particular Department has many Employees and hence a Parent-Child relationship.
    Firstly, you need to create an Association between the two Entities - Department and Employees. You can do that by right clicking on the model's entity and then associating the two entities with the appropriate key say, DepartmentId.
    Once you have done that, you need to link the two entities in the View section with this Association that you created. Then go to AppModule and make sure that in the Available View Objects: 'EmployeesView' appears under 'DepartmentView' as "EmployeesView via <link you created>". Shuttle the 'DepartmentView' to the right, Data Model and then shuttle
    "EmployeesView via <link you created>" to the right, Data Model under 'DepartmentView'.
    This will then be reflected in your Data Controls. After that, you simply would have to drag this View into your page as a Master-Detail form...and then when you run this page, any row selected in the Master table, would display the data in the Detail table.
    Also, refer to this link: [Master-Detail|http://baigsorcl.blogspot.com/2010/03/creating-master-detail-form-in-adf.html]
    Hope this helps.

  • Selecting from one table and Update another in the same Page

    Could someone help me with this HTMLDB task. In my page design, I am selecting data from two tables (masters: DEPT, EMP) which I want to display on the left column of the page and at the same time a user would be able to update another table (ATTENDANCE:with many children) which would have a radiogroup on the right side for each value of the master such as employee name. The placement of data has to appear in corresponding rows on the page. For instance, employee names of the master table must appear on the same row with its corresponding child value. The page would be grouped by DEPT_NO. The user would click on the department name, a new page with the employee name would apprar. From that page, the user would then update attendance column for each employee in that department. In this operation, it is only the ATTENDANCE table that is being updated. I can send out more information about the structure of the tables if you need more information. I tried many HTMLDB options, forms, reports, etc. I have not been able to get quite right. Your help will be appreciated.

    Raju,
    Thanks for responding to my problem. I have actually tried using the example on how-to you sent me a link to but it did not help as I expected. You see, the page would be updated every meeting date for each employee. I can send you more information about the table structure if you like. However, let me see if this will help you a bit.
    Tables are: 1) Dept [dept_no (pk),dept_name] 2) EMP [emp_no (pk),emp_name, dept_no(fk)] 3) Meetings [meet_key(pk),attended, meeting_date, emp_no(fk)]
    What I want to do is create two pages, one would list the departments, when a user selects a department, the user would be linked to a meeting attandance page. The meeting attendance page would list department name once, Meeting date once, and then list employees in that department. At the right column of every employee would be a checkbox for meeting.attended for update. The meeting_date would be pre-populated so that what the user would do is just check Yes/NO. The second page is the one I'm having the most problem with.
    If I can do a fetch from dept, emp, and meetings and then do an update on the Meetings table on the same page, I think that might solve the problem. That was how I solved it in MS Access three years ago.
    Here is email address in case you want to contact me directly. [email protected]
    Thanks again for your help.

  • How to avoid ORA-3113 when selecting from XMLTYPE table

    Hi,
    If I register an XML-schema, Oracle automatically creates a table xxxxxx_tab of XMLTYPE. (I use Oracle 9.2.0.1)
    When I do a DESCRIBE or a SELECT from this table I get the error: 'ORA-03113:
    end-of-file on communication channel' and my connection is dropped.
    I opened a TAR for this and Oracle says: 'It is an internal bug so cannot be viewed in metalink. This is fixed in release 10i.' (do they mean oracle DB rel 10i, or a new version of XDK?)
    I saw an example in Oracle Magazine (Jan
    2003) "Make XML Native and Relative" about Oracle 9i Rel 2 and XML. As you can see in codeListing 7, the author also does a select from such a
    table (CD331_tab): Why doesn't he have any problems?
    Is there a workaround for this bug? What's the purpose of being able to automatically upload XML-data to a registered schema if you can't do a select of the data?
    Thank you!

    It appears that the XML Schema is not entirely valid. Specifically, the definition of element "DeviceCategory" has two definitions of element "Audio" appearing within a <choice> model i.e. something like :
    <element name="DeviceCategory">
    <choice>
    <sequence>
    <element name="Audio">
    </sequence>
    <sequence>
    <element name="Audio">
    </sequence>
    </choice>
    This is disallowed by XML Schema spec per. the Unique Particle Attribution Constraint. The general idea is that a XML Schema describes a determinstic content model i.e. schema processor can always unambiguosly determine the matching declaration when it encounters an element. However that's not the case with the declaration above. On encoutering "Audio", it could match either the first or the second declaration of the element. Hence the error.
    You will have to rework the schema to avoid this constraint. One mechanism could be to define complexType and their restrictions.
    - Ravi

Maybe you are looking for

  • How do I set up my TC to be 2.4GHZ for my iphone but 5GHZ for my Macbook?

    On an older 500 GB TC, how do I set it up so that my MacBook can receive 5GHZ but still allow my iphone to work on 2.4GHZ? Is there a way to do this with the older TC's?

  • After iphoto update i can't delete pictures

    Yesterday after the new updtae i can't delete pictures and after some time iphoto gives nor respones. can someone help please? sorry for bad english

  • Iso image playing in windows, but not in mac

    torrent site for the iso image is: http://isohunt.com/torrent_details/119383481/ccie?tab=summary#.UGby8mg1FFI it's a cisco network concept tutorial, it is playing on a windows laptop on windows xp, vista or 7. I understand that wmv player cannot be p

  • Export Layers as Files - Please Help on Error Message

    Hi, Not sure if I'm doing the right thing anyway, but I'm trying to export all the layers in one file as separate JPGs. Each layer has its own name and ideally, i would like to save each layer as its layer name. When I choose the script 'export layer

  • Dump DBIF_RSQL_INVALID_REQUEST on cluster tables

    Hi! I am having a brand new fresh SAP installation which produces a dump DBIF_RSQL_INVALID_REQUEST on any attempt to access any cluster table such as BSEG or DOKTL. The note 128617 "DBIF_RSQL_INVALID_REQUEST w/accessing cluster table" describes a ver