sql server - Is there a better way to optimize the sql query using Linq? -


i trying count details 2 tables.the count depends on table1.data field below query

select 'all'    type,  count(*) cnt    table1  inner join table2  on table1.id = table2.id   table1.id = 2683   union  select 'no type' type,  count(*) cnt    table1  inner join table2  on table1.id = table2.id   table1.id = 2683  , isnull(table1.data, '') = ''   union  select isnull(table1.data, '') type,  count(*)                    cnt    table1  inner join table2  on table1.id = table2.id   table1.id = 2683  , isnull(table1.data, '') <> ''  group  isnull(table1.data, '')  

and output should be

type             cnt --------------  -----               4 no type           0 type1             3 

i trying use case statements failed.any suggestions please. updated actual sql query is

select 'all'    floornotetype,         count(*) cnt    floor_notes         inner join floor_note_xref                 on floor_notes.floor_note_id = floor_note_xref.floor_note_id   floor_note_xref.inmate_id = 2683  union  select 'no type',         count(*) cnt    floor_notes         inner join floor_note_xref                 on floor_notes.floor_note_id = floor_note_xref.floor_note_id   floor_note_xref.inmate_id = 2683         , isnull(floor_note_type, '') = ''  union  select isnull(floor_note_type, '') floornotetype,         count(*)                    cnt    floor_notes         inner join floor_note_xref                 on floor_notes.floor_note_id = floor_note_xref.floor_note_id   floor_note_xref.inmate_id = 2683         , isnull(floor_note_type, '') <> ''  group  isnull(floor_note_type, '')  

you can retrieve totals using single query with rollup clause:

select   case when              grouping(table1.data) = 1 'all'        else              isnull(table1.data, 'no type')   end type,   count(*) cnt      table1      inner join table2 on table1.id = table2.id   table1.id = 2683  group  table1.data rollup 

with rollup generates hierarchical sub-totals each field in group by clause way grand total.

fields don't take part in sub-total have null value, means null keys , subtotals can mixed up. grouping(..) function checks see whether result row grand total specific field.

in case there single grouping field, grouping(table1.data) return 1 row corresponds grand total


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -