Click here to Skip to main content
15,896,469 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
SQL
  Id    Status                                  Number
1242    P                                   5.25
   3    P                                   7.5
  11    P                                   9
  19    P                                   9
  36    P                                   9
   3    F                                   0
   4    F                                   0
   9    F                                   3.75
  19    F                                   3.75



Sum of number having status 'P' and those 'F' have id which is not in status 'P'.

I mean sum of 1242(P),3(P),11(P),19(P),36(P),4(F),9(F) ... Ignore these 2 rows 3(F) and 19(F).

Thank You!
Posted
Comments
Kornfeld Eliyahu Peter 7-Jul-15 8:19am    
Ignored them...
But what have YOU tried?[^]

1 solution

There is a trick to this.

The issue is that any groupings you apply will not effect the sum. You need a Common Table Expressions(CTE)[^].

Read up on it because they are so powerful

So, your query might look like this:
SQL
WITH myCTE1 as (
  SELECT Id, Status, Number
  From table
  where Status = 'P'),
myCTE2 as (
  Select t.Id, t.Status, t.Number
  From table t
  where t.Status = 'F'
  AND NOT EXISTS (SELECT * FROM myCTE1 WHERE Id = t.Id)
  UNION SELECT Id, Status, Number
  FROM myCTE1)

SELECT sum(Number), Status FROM myCTE2 GROUP BY Status 
 
Share this answer
 
Comments
Afzal Shaikh 8-Jul-15 3:39am    
Thank you , It works :)
Andy Lanng 8-Jul-15 4:13am    
np. CTE's are very powerful because the queries are only assessed based on their usage. They are VERY efficient in any case.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900