views:

129

answers:

3

I am trying to calculate the total rows in a table called DRAWING with the following query: Select field, platform, count(doc_id) as total from drawing group by field, platform;

but I also need to display the total of attachments/non-attachments for each platform

SQL:

select field,platform,count(doc_id) as attached from drawing where file_bin is not null group by field, platform;

select field,platform,count(doc_id) as non_attached from drawing where file_bin is null group by field, platform;

Is there a way to combine the 3 values into a view? e.g Field , Platform, Total, Attached, Non_attached

+1  A: 

Try this:

select 
  field, 
  platform, 
  count(doc_id) as total,
  sum(iif(file_bin is null, 1, 0)) as attached,
  sum(iif(file_bin is not null, 1, 0)) as non_attached
from drawing 
where doc_id is not null 
group by field, platform
Douglas Tosi
sum(iif(file_bin is null, 1, 0)) as attached, *ERROR at line 5:ORA-00907: missing right parenthesisI must have missed something, can you clarify? thank you
A: 

thanks to Douglas Tosi's suggestion, I managed to use the case method instead.

select field, platform, count(doc_id) as total, Sum(CASE WHEN file_bin is null THEN 1 WHEN file_bin is not null THEN 0 END) as attached, Sum(CASE WHEN file_bin is null THEN 0 WHEN file_bin is not null THEN 1 END) as non_attached from drawing where doc_id is not null group by field, platform

perfect!!

Thanks again Douglas

A: 

I would use decode instead of case, don't know what performs better (untested):

select field
,      platform
,      count(doc_id) as total
,      sum(decode(file_bin,null,1,0)) attached 
,      sum(decode(file_bin,null,0,1)) non_attached
from   drawing 
where  doc_id is not null 
group by field,platform
tuinstoel
I've searched on some posts and found that decode has the same performance as case. Decode would be quite suitable for my table, thanks. Though case has an advantage for SQL statements that need nested conditional statements