Difficult Query

Hello, I am new to Transact SQL and am not sure how to get the proper result set.  If there is OE 1 and only EP 1 for the same sysprojn (see 3000021), I only want to select the row with the OE 1.  If there are more EP rows for the same sysprojn (see 3000024) then the sum(bookd) of the EP rows equals the bookd of the OE.  In that case, I need to select all the EP rows and the OE row.  Any help would be greatly appreciated.  Thank you.

sysprojn   type   no   bookd
3000020    OE     1    201684
3000021    EP     1    1633842
3000021    OE     1    1633842
3000022    OE     1    850731
3000023    EP     1    201684
3000023    EP     2    0
3000023    OE     1    201684
3000024    EP     1    1152501
3000024    EP     2    481341
3000024    OE     1    1633842
3000025    OE     1    7655823
3000026    EP     1    1152501
3000026    EP     2    481551
3000026    EP     3    -210
3000026    OE     1   1633842


Answer this question

Difficult Query

  • Mu0n

    Yes, your answer helped tremendously.  Thanks Josh! 
  • GregQuinn

    Can you post the expected results I didn't get the 2nd part of the problem about the sum.

  • Brandon Taylor

    Do you need to perform the calculation, or just limit the rows   My interpretation was the latter, in which case you just need to remove any EP rows where there aren't at least 2 EP records.  If so:


    SELECT *
    FROM <some_table>
    MINUS
    SELECT *
    FROM <some_table>
    WHERE type='EP'
    AND sysprojn in 
       (SELECT sysprojn, COUNT(sysprojn) 
       FROM <some_table> 
       WHERE type='EP'
       GROUP BY sysprojn 
       HAVING COUNT(sysprojn)<2)
    GO

     


    Hope this helps,
    Josh



  • Difficult Query