sql - merge two queries with different where and different grouping into 1 -
sorry, asked question before , got answers realised made mistake query in question, if change question in original post make answers invalid i'm posting again right query time, please forgive me, hope acceptable.
declare @temp table (measuredate, col1, col2, type) insert @temp select measuredate, col1, col2, 1 table1 col3 = 1 insert @temp select measuredate, col1, col2, 3 table1 col3 = 1 , col4 = 7000 select sum(col1) / sum(col2) percentage, measuredate, type @temp group measuredate, type
i 2 inserts temp table, 2nd insert same columns same table, different type, sum(col1) / sum(col2) on temp table return result need per measuredate , type. there way merge these inserts , selects 1 statement don't use temp table , single select table1? or if still need temp table, merge selects 1 select instead of 2 separate selects? stored procedure works fine is, looking way shorten it.
thanks.
sure can. might start combining 2 queries inserts using union all
(this variation of union
not remove duplicates), wrapped in cte can perform final query:
with measuredata(measuredate, col1, col2, type) ( select measuredate, col1, col2, 1 table1 col3 = 1 union select measuredate, col1, col2, 3 table1 col3 = 1 , col4 = 7000 ) select sum(col1) / sum(col2) percentage, measuredate, type measuredata group measuredate, type
that's it, no more table variable or insert statements.
Comments
Post a Comment