Help with this sql. Select only employees from a distinct Org??

Hi guys, simple query.
create table balancetest(emp_id number, balance_id number, balance number, org number);
insert into balancetest values (111, 1, 1, 0);
insert into balancetest values (111, 1, 1, 0);
insert into balancetest values (111, 2, 1, 1);
insert into balancetest values (222, 1, 2, 1);
insert into balancetest values (333, 3, 4, 3);
insert into balancetest values (333, 3, 4, 2);
commit;
SQL> select * from balancetest;
    EMP_ID BALANCE_ID    BALANCE        ORG
       111          1          1          0
       111          1          1          0
       111          2          1          1
       222          1          2          1
       333          3          4          3
       333          3          4          2
6 rows selected.As you can see, emp_id 111 appears on different Org (0 and 1). I need to calculate the balance but the requirement says that I need to retrieve employees appearing only in 1 org.. It won't matter which org is selected (the business rules ensure balance will be the same), as long as if an employee is in multiple org, this employee is selected only once for an org. So, my result will be something like:
    EMP_ID BALANCE_ID    BALANCE        ORG
       111          1          1          0
       111          1          1          0
       222          1          2          1
       333          3          4          3
       333          3          4          2or,
    EMP_ID BALANCE_ID    BALANCE        ORG
       111          2          1          1
       222          1          2          1
       333          3          4          3
       333          3          4          2In other words, an employee must appear only in 1 org in my result.
any ideas? I tried:
select * from balancetest bal1
where not exists ( select bal2.emp_id from
                           balancetest bal2
                           where bal2.emp_id = bal1.emp_id
                           and bal2.org <> bal1.org
                           );But I guess it won't be that simple!!

Hi,
You can find the lowest-numbered org for each employee like this:
SELECT    emp_id
,         MIN (org)  AS min_org
FROM      balancetest
GROUP BY  emp_id;You can get the results you want by selecting only rows from balancetest that match a row in this the result set above. There are many ways to do that, such as a join:
WITH  g  AS
    SELECT    emp_id
    ,         MIN (org)  AS min_org
    FROM      balancetest
    GROUP BY  emp_id
SELECT  b.*
FROM    balancetest  b
JOIN                 g  ON  b.emp_id = g.emp_id
                        AND b.org    = g.min_org;

Similar Messages

  • Anybody can help with this SQL?

    The table is simple, only 2 columns:
    create table personpay(
    id integer primary key,
    pay number(8,2) not null);
    So the original talbe looks like this:
    ID PAY
    1 800
    2 400
    3 1200
    4 500
    5 600
    6 1900
    The requirement is to use one single query(no pl/sql) to show something lile the following, in other words, for each ID, the pay is the sum of all before itself and itself. So the query result looks like this:
    ID PAY
    1 800
    2 1200
    3 2400
    4 2900
    5 3500
    6 5400
    Again, just use one sql. No pl/sql. Anybody can help with this? I really appreciate that.
    thanks,

    Eh, people are so "analytically minded" that can't even notice a simple join?
    Counting Ordered Rows
    Let’s start with a basic counting problem. Suppose we are given a list of integers, for example:
    x
    2
    3
    4
    6
    9
    and want to enumerate all of them sequentially like this:
    x      #
    2      1
    3      2
    4      3
    6      4
    9      5
    Enumerating rows in the increasing order is the same as counting how many rows precede a given row.
    SQL enjoys success unparalleled by any rival query language. Not the last reason for such popularity might be credited to its proximity to English . Let examine the informal idea
    Enumerating rows in increasing order is counting how many rows precede a given row.
    carefully. Perhaps the most important is that we referred to the rows in the source table twice: first, to a given row, second, to a preceding row. Therefore, we need to join our number list with itself (fig 1.1).
    Cartesian Product
    Surprisingly, not many basic SQL tutorials, which are so abundant on the web today, mention Cartesian product. Cartesian product is a join operator with no join condition
    select A.*, B.* from A, B
    Figure 1.1: Cartesian product of the set A = {2,3,4,6,9} by itself. Counting all the elements x that are no greater than y produces the sequence number of y in the set A.
    Carrying over this idea into formal SQL query is straightforward. As it is our first query in this book, let’s do it step by step. The Cartesian product itself is
    select t.x x, tt.x y
    from T t, T tt
    Next, the triangle area below the main diagonal is
    select t.x x, tt.x y
    from T t, T tt
    where tt.x <= t.x
    Finally, we need only one column – t.x – which we group the previous result by and count
    select t.x, count(*) seqNum
    from T t, T tt
    where tt.x <= t.x
    group by t.x
    What if we modify the problem slightly and ask for a list of pairs where each number is coupled with its predecessor?
    x      predecessor
    2      
    3      2
    4      3
    6      4
    9      6
    Let me provide a typical mathematician’s answer, first -- it is remarkable in a certain way. Given that we already know how to number list elements successively, it might be tempted to reduce the current problem to the previous one:
    Enumerate all the numbers in the increasing order and match each sequence number seq# with predecessor seq#-1. Next!
    This attitude is, undoubtedly, the most economical way of thinking, although not necessarily producing the most efficient SQL. Therefore, let’s revisit our original approach, as illustrated on fig 1.2.
    Figure 1.2: Cartesian product of the set A = {2,3,4,6,9} by itself. The predecessor of y is the maximal number in a set of x that are less than y. There is no predecessor for y = 2.
    This translates into the following SQL query
    select t.x, max(tt.x) predecessor
    from T t, T tt
    where tt.x < t.x
    group by t.x
    Both solutions are expressed in standard SQL leveraging join and grouping with aggregation. Alternatively, instead of joining and grouping why don’t we calculate the count or max just in place as a correlated scalar subquery:
    select t.x,
    (select count(*) from T tt where tt.x <= t.x) seq#
    from T t
    group by t.x
    The subquery always returns a single value; this is why it is called scalar. The tt.x <= t.x predicate connects it to the outer query; this is why it is called correlated. Arguably, leveraging correlated scalar subqueries is one the most intuitive techniques to write SQL queries.
    How about counting rows that are not necessarily distinct? This is where our method breaks. It is challenging to distinguish duplicate rows by purely logical means, so that various less “pure” counting methods were devised. They all, however, require extending the SQL syntactically, which was the beginning of slipping along the ever increasing language complexity slope.
    Here is how analytic SQL extension counts rows
    select x, rank() over(order by x) seq# from T; -- first problem
    select x, lag() over(order by x) seq# from T; -- second problem
    Many people suggest that it’s not only more efficient, but more intuitive. The idea that “analytics rocks” can be challenged in many ways. The syntactic clarity has its cost: SQL programmer has to remember (or, at least, lookup) the list of analytic functions. The performance argument is not evident, since non-analytical queries are simpler construction from optimizer perspective. A shorter list of physical execution operators implies fewer query transformation rules, and less dramatic combinatorial explosion of the optimizer search space.
    It might even be argued that the syntax could be better. The partition by and order by clauses have similar functionality to the group by and order by clauses in the main query block. Yet one name was reused, and the other had been chosen to have a new name. Unlike other scalar expressions, which can be placed anywhere in SQL query where scalar values are accepted, the analytics clause lives in the scope of the select clause only. I have never been able to suppress an impression that analytic extension could be designed in more natural way.

  • Need help with this sql query

    the following query returns me the correct no of rows:
    select col1 from tab1 where
    col1 like '%'||chr(32)||'%';
    but i need to use my query in the following form and it doesn't return any row:
    select col1 from tab1 where
    col1 IN ('%'||chr(32)||'%');
    what am I doing worng?
    thanks in advance.

    Or in 10g (just recycling another example):
    WITH t AS (SELECT 'OPTI1457' || CHR(32) col1
                 FROM dual
                UNION
               SELECT 'OPT123' || CHR(9)
                 FROM dual
                UNION
               SELECT 'OPTIM12345'
                 FROM dual
    SELECT t.*
      FROM t
    WHERE REGEXP_LIKE(t.col1, CHR(32) || '|' || CHR(9))
    ;       C.

  • Need Help with this SQL Report

    Declare @Total int
    Select
    @Total=count(*)
    From
    v_Add_Remove_Programs
    Where
    v_Add_Remove_Programs.DisplayName0 Like '@DisplayName'
    Select Distinct
    v_Add_Remove_Programs.DisplayName0 as [Software Product],
    Version0 as [Version],
    COUNT(v_GS_System.Name0) as [Count],
    Round(100.0*count(*)/@Total,1) as [Percentage]
    FROM
    v_Add_Remove_Programs
    Join
    v_GS_System ON v_Add_Remove_Programs.ResourceID = v_GS_System.ResourceID
    WHERE
    v_Add_Remove_Programs.DisplayName0 Like '@DisplayName'
    GROUP BY
    Version0,
    v_Add_Remove_Programs.DisplayName0
    ORDER BY
    [Percentage] DESC
    Select Distinct
    v_GS_SYSTEM.Name0 as [Computer Name],
    v_Add_Remove_Programs.DisplayName0 as [Software Product],
    Version0 as [Version]
    FROM
    v_Add_Remove_Programs
    Join
    v_GS_SYSTEM ON v_Add_Remove_Programs.ResourceID = v_GS_SYSTEM.ResourceID
    WHERE
    v_Add_Remove_Programs.DisplayName0 Like '@DisplayName'
    GROUP BY
    v_GS_SYSTEM.Name0,
    Version0,
    v_Add_Remove_Programs.DisplayName0
    ORDER BY
    [Version] DESC
    If I remove the @DisplyaName variables and type in a product name sucha as:
    = 'Microsoft Office Professional 2013" or something, it works fine. How can I get the @DisplayName variables to work for me?
    Thanks

    v_Add_Remove_Programs.DisplayName0 Like '%'+ @DisplayName+'%'

  • Still having problem with this sql select... any suggestions!  tx

    The following code has a result, I need to modify the select somehow which only gives me the rows which are common between all PLSTS.
    Any suggestions?
    Thank you
    SELECT DISTINCT P.PLST, P.MENU, I.PNL, P.ACCESS
    FROM AUTHITEM P, I.MENUITEM
    WHERE P.MENU = I.MENU
    AND P.PNL = I.PNL
    AND P.MENU IN ('MSN, CPP')
    AND P.ACESS >= 8
    AND EXISTS
    (SELECT K.PLST,COUNT (*)
    FROM AUTHITEM K, J.MENUITEM
    WHERE K.MENU = J.MENU
    AND K.PNL = J.PNL
    AND P.MENU = K.MENU
    AND I.PNL = J.PNL
    --AND P.PLST !=K.PLST
    --HAVING COUNT(*)   =2
    GROUP BY P.PLST, PMENU, I.PNL, P.ACCESS)
    This is the result with having count (*) = 2 and plst !=plst comment
    PLST MENU PNL ACCESS
    C001 MSN LNAME 14
    C002 MSN LNAME 14
    B008 MSN LNAME 14
    B005 MSN FNAME 14
    M009 MSN LNAME 14
    C001 MSN GNAME 14
    C002 MSN GNAME 14
    B008 MSN LNAME 14
    C001 MSN FNAME 14
    C002 MSN FNAME 14
    k008 CPP MNAME 14
    If I add having count (*) = 2, I do not get any results
    I need this result
    PLST MENU PNL ACCESS
    C001 MSN LNAME 14
    C002 MSN LNAME 14
    C001 MSN GNAME 14
    C002 MSN GNAME 14
    C001 MSN FNAME 14
    C002 MSN FNAME 14
    Thank you

      > I need this result
      > PLST MENU PNL   ACCESS
      > C001 MSN  LNAME 14
      > C002 MSN  LNAME 14
      > C001 MSN  GNAME 14
      > C002 MSN  GNAME 14
      > C001 MSN  FNAME 14
      > C002 MSN  FNAME 14
    i think based on your original posting what you need on your groupings are the columns MENU, PNL, ACCESS and exclude PLST.
      SELECT DISTINCT P.PLST, P.MENU, I.PNL, P.ACCESS
        FROM AUTHITEM P, I.MENUITEM
       WHERE P.MENU = I.MENU
         AND P.PNL  = I.PNL
         AND P.MENU IN ('MSN, CPP')
         AND P.ACESS >= 8
         AND EXISTS (SELECT 'x'
                       FROM AUTHITEM K, J.MENUITEM
                      WHERE K.MENU = J.MENU
                        AND K.PNL  = J.PNL
                        AND P.MENU = K.MENU
                        AND I.PNL  = J.PNL
                        AND P.PLST !=K.PLST
                     HAVING COUNT(*) = 2
                     GROUP BY PMENU, I.PNL, P.ACCESS)note: untested

  • Help with this SQL Query please

    How many garments has each dressmaker constructed? You should give the number of garments and the name, house number and post code of each dressmaker.
    tables; dressmaker contains D_NO, D_NAME, D_HOUSE_NO, D_POST_CODE
    garment contains STYLE_NO, DESCRIPTION, LABOUR_COST, NOTIONS
    quantities contains STYLE_Q, SIZE_Q, QUANTITY
    The question title is multitableJOINS
    I believe i have to use (garment.style_no=quantities.style_q) if it will work, im new to oracle & SQL so all the help i get i am grateful for, thankyou.

    Not to be a jerk, but this forum is really not intended for homework. Show a little effort, and try it out. Post some results, and maybe someone will help you out. Getting others to do your homework will not help you when you get out of school.

  • I just downloaded an album from itunes and 2 of the tracks will not play at all, they cut off. I need help with this??

    I just downloaded an album from itunes and 2 of the tracks will not play at all, they cut off. I need help with this??

    Does the track play correctly in Quicktime Player?  If it does then it is an iTunes issue.  If it doesn't then it is possible the file was not completely downloaded, or is corrupt.
    Downloading (using iOS or computer) past purchases from the App Store, iBookstore, and iTunes Store - http://support.apple.com/kb/ht2519 - enabled with iTunes 10.3 and newer; not available in all countries; apps, books (not audiobooks), music, t.v. shows, and movies (some - not all studios have permitted this). Movies currently available in the USA only. Downloading previously purchased movies and TV shows requires iTunes 10.6 or later.  Discontinued items not available. For items not included in the iCloud list (e.g., ringtones), or locations or computer systems where iCloud is not (yet?) available, you only get one download per fee paid. 
    If it can be downloaded again, delete the track from iTunes.
    Select the store on the left side of iTunes.
    Click on Purchased on the right side under Quick Links.
    You can re-download your available previous purchases.
    If it is corrupt and you cannot download it a second time, contact Apple.  Contact iTunes Store support staff through the report a problem links in your account history or,
    iTunes Customer Service Contact - http://www.apple.com/support/itunes/contact.html > Get iTunes support via Express Lane > iTunes > iTunes Store

  • TS3999 I am unable to sync my Outlook calendar with my Iphone. I have noted that the Icloud Outlook add in is not ticked When I attempt to load it from the designated file nothing happens Can anyone help with this? Robyn

    I am unable to sync my Outlook calendar with my Iphone. I have noted that the Icloud Outlook add in is not ticked When I attempt to load it from the designated file nothing happens Can anyone help with this? Robyn

    Re: check that the appointments in my phone are going into iCloud calendars....exactly how do I do this?  I fear this is a really stupid question!
    My iCloud account is set up with my Apple ID as one email account (for example [email protected]) which is the email account I use to sign up for internet sites like Amazon, Apple,etc, so that I can differentiate vendors/mass emails.  But my default calendar on my iPhone is in a different email name (ie [email protected]) which I use for most communications to friends, relatives, etc. and it is this account that holds most of my appointments.  To further complicate things I have other email accounts that I use for business/professional and community work.  If I want all my calendars to show on my iPhone AND sync to my iCloud, do I set this at the phone level or the iCloud level?  or both?   
    Let me clarify....It looks like if I go into appointments that I previously set up through my personal account (ie above [email protected]) and edit the entry on my iPhone, selecting the iCloud "home" calendar within the entry, it will then sync to my iCloud account, no problem....do I have to do this to EVERY entry I have? or is there  a way to name my personal account as one to sync to iCloud?

  • HT2534 If only it were that simple. Many of us have no "none" available.  Since the guy on the other discussion clearly had no desire to help anyone, I thought I'd ask here instead... can anyone help with this?

    If only it were that simple. Many of us have no "none" available.
    Since the guy on the other discussion clearly had no desire to help anyone, I thought I'd ask here instead... can anyone help with this?

    Open iTunes and navigate to the app store. Select a free app to download. A simple way to do this is to scroll down to the top free apps box on the right hand side, hover your mouse over the first item and click on the free button that appears when you hover over it.
    A pop up will open asking you to sign in with your Apple ID click "create new account", click continue to create your account. Check the box to accept the store terms and conditions and click continue.
    Enter your email address, password, security question, and date of birth, click continue. Now, you will be asked to provide a payment method. Note now that the last option says "none".

  • HT4356 I'm using my iPod and an Epson XP-810 printer to print pages from websites and emails and etc.  How do I print just 1 page out of 14 pages .  I don't see any settings on my iPod and can't find settings on the printer .   Can someone help with this

    I'm using my iPod and an Epson XP-810 printer to print pages from websites and emails and etc. 
    How do I print just 1 page out of 14 pages . 
    I don't see any settings on my iPod and can't find settings on the printer .  
    Can someone help with this problem

    Google show that you have to cut what you want to print and then paste it into a new app and print from that app.
    http://www.ipadforums.net/new-member-introductions-site-assistance/63145-printin g-one-page-ipad-2-a.html

  • Hello, I would like to download my contacts from icloud to a flash drive in order to print out.  Can anyone help with this?  Many thanks

    Hello, I would like to download my contacts from icloud to a flash drive in order to have them printed out as I have over 4,000 contacts.  Could anyone help with this?  Thank you

    This  this discussion >  https://discussions.apple.com/message/24150181#24150181

  • I recently updated my computer to 10.6 and now I can't get my printer MX340 (canon ) to work. I have installed the new drivers both from Canon's website and from an earlier post directly from apples website. I would surely appreciate some help with this.

    I recently updated my computer to 10.6 and now I can't get my printer MX340 (canon ) to work. I have installed the new drivers both from Canon's website and from an earlier post directly from apples website. I would surely appreciate some help with this.

    Try what Terence Devlin posted in this topic:
    Terence Devlin
    Apr 14, 2015 11:21 AM
    Re: Is Iphoto gone ? i want it back!
    in response to Johannes666
    Recommended
    Go to the App Store and check out the Purchases List. If iPhoto is there then it will be v9.6.1
    If it is there, then drag your existing iPhoto app (not the library, just the app) to the trash
    Install the App from the App Store.
    Sometimes iPhoto is not visible on the Purchases List. it may be hidden. See this article for details on how to unhide it.
    http://support.apple.com/kb/HT4928
    One question often asked: Will I lose my Photos if I reinstall?
    iPhoto the application and the iPhoto Library are two different parts of the iPhoto programme. So, reinstalling the app should not affect the Library. BUT you should always have a back up before doing this kind of work. Always.

  • Hi I got an email from itunes saying that my pre order was ready and when I click on the link from my ipad it takes me to the itunes store app and then it doesn't do anything help with this please.

    Hi I got an email from itunes saying that my pre order was ready and when I click on the link from my ipad it takes me to the itunes store app and then it doesn't do anything help with this please .
    <Link Edited By Host>

    Thanks for your advice, I went to the apple shop today for a face to face meeting with a tech and he checked everything and could not figure out why I was having this problem so we decided to give up on that account and create a whole new one for me using a different email address.
    Now I can download apps on both my iPhone and ipad2.
    If anyone is reading this in Brisbane Australia go to the Chermside apple shop and ask for Wade. He was fantastic!
    Jan

  • After updating my iphone 4 i now cant open picture texts from a samsung galaxy 2s. can anyone help with this?

    after updating my iphone 4 i now cannot open picture texts from a samsung galaxy 2s. all i get is the text with a box with the picture file size and a question mark to the left of the box. It has also done the same to the already opened pictures I had received prior to updating my iphone. can anyone help with this ??

    Check for hardware issues
    Try to restore your iOS device two more times while connected with a cable, computer, and network you know are good. Also, confirm your security software and settings are allowing communication between your device and update servers. If you still see the alert when you update or restore, contact Apple support.
    Common errors: 1, 10-47, 1002, 1011, 1012, 1014, 1000-1020.
    The above comes from here:
    http://support.apple.com/kb/TS3694#47

  • My "fn" button is stuck on only revealing mission control in Lion. With this problem none of my "f" keys will work nor can I hold "fn" and delete to delete text in opposite direction. Can someone please help with this?

    My "fn" button is stuck on only revealing mission control in Lion. With this problem none of my "f" keys will work nor can I hold "fn" and delete to delete text in opposite direction. Can someone please help with this?

    Following the fix here worked for me:
    https://discussions.apple.com/message/15680566#15680566
    except my plist file was in ~/Library instead of /Library.
    -Scott

Maybe you are looking for

  • How do i get my library back after setting up seperate users in vista

    Hello all.  After much frustration, I have decided to turn to my piers for help. (I tried to go thru apple support but they wanted to charge me)   I have three devices that sync to my computer - my iphone, and two itouch's that belong to my daughers.

  • HT201303 How can I have my iPhone and my iPad with the same Apple ID?

    I recently bought an iPad and I want to have it on the same Apple ID that I currently have on my iPhone 5. I want to be able to play my current game (Boombeach), which I started on my iPhone5, on my new iPad. Can anyone help with these problems?

  • Selection screen validation in HR ad hoc query

    Hi Experts, I have created a query in SQ01. My infoset is created using Logical database PNPCE. Selection criteria contains Fields  Personnel Number and Employment status. so when the query will be run, I want to display error message if invalid pers

  • Event structure in a subVI

    I know this problem has been posted, but I've already am passing everything by reference. I can't get my subVI to respond to my top layer VI. It runs fine as a stand alone, but when I ask it to monitor events from a reference, it won't do anything. I

  • How to transfer music?

    I am really sorry for sounding stupid.....but I am really not getting how to transfer music to my sd card....I have followed the instructions in the manual.....and all it says is that you can drag and drop files with your desktop manager...I have tri