1

I have two tables l & C which are linked by two fields l.mID and c.mID the c table holds three types of records cs, ls, & vs with my query I need to select all records from l and as part of the query have three columns showing totals for cs, ls & vs;

SO far I am using an outer join:

SELECT l.*, COUNT(*) FROM l LEFT OUTER JOIN c ON c.mID = l.mID WHERE l.mID = 2

But this just appends one column with a full total any help would be great thanks.

4
  • By totals, do you mean SUM() for each of those columns? Commented Jul 24, 2012 at 15:12
  • It might be useful in this case to show sample data for the tables and to explain what aggregation you are attempting to do. Commented Jul 24, 2012 at 15:13
  • Please provide sample data and desired output. Commented Jul 24, 2012 at 15:13
  • As per juergen below this is what I would like to achieve however I am getting multi plicated values 5 is bemiring 25 any reason for this? Commented Jul 25, 2012 at 15:53

2 Answers 2

2

You can use a CASE statement in your count:

select
  l.*
  ,COUNT(CASE WHEN c.type = 'cs' then 1 END) as cscount
  ,COUNT(CASE WHEN c.type = 'ls' then 1 END) as lscount
  ,COUNT(CASE WHEN c.type = 'vs' then 1 END) as vscount
from l
left outer join c on c.mID = l.mID
where l.mID = 2
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks buddy really helpful and a great solution to my issue :)
1
select
  l.*
  ,sum(c.type = 'cs') as cscount
  ,sum(c.type = 'ls') as lscount
  ,sum(c.type = 'vs') as vscount
from l
left outer join c on c.mID = l.mID
where l.mID = 2

1 Comment

Thanks for this however it seems to multiply the values i.e. 5 becomes 25 any thoughts? I have repeating lines in the l table as it is a view

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.