SQL Server--Is it possible to work around using a temporary table for a query that filters based on an alias case column? -
i trying alter base query selects data several joined tables, , filters out rows based on case when below. result set returned follows:
if of rows return 0 in
casecolumn, return 1 line '0' inoverduecolumn (the "return 1 line" portion taken care ofdistinct.)if of rows return 1
casecolumn, return 1 line '1' inoverduecolumn.
the base follows:
select distinct t1.*, case when t3.mtemp > t3.mtemplimit 1 when t3.tothours > t3.thourslimit 1 else 0 end [overdue] table_1 t1 left join table_2 t2 on t1.resno = t2.resno , t1.pcode = t2.pcode left join table_3 t3 on t2.repjobno = t3.repjobno left join table_4 t4 on t4.typeid = t2.reptype t2.repstat = 1 the catch is, i've created working version of using temp table , doing if exists/else query on temp table's overdue column. however, i've been informed solution may not useable (due having go through front-end software).
is possible workaround not involve using temporary table? i've been making attempts @ using both derived table , ctes, neither of have yielded usable, due fact 1 cannot use if/else clauses after (which counting on).
i'm still getting hang of t-sql, appreciated.
sounds simple row_number() , couple of ctes work:
;with rs1 ( select t1.*, case when t3.mtemp > t3.mtemplimit 1 when t3.tothours > t3.thourslimit 1 else 0 end [overdue] table_1 t1 left join table_2 t2 on t1.resno = t2.resno , t1.pcode = t2.pcode left join table_3 t3 on t2.repjobno = t3.repjobno left join table_4 t4 on t4.typeid = t2.reptype t2.repstat = 1 ), rs2 ( select *,row_number() on (order overdue desc) rn rs1 ) select * rs2 rn = 1 (there's no need distinct we're returning 1 row)
Comments
Post a Comment