Thursday, August 11, 2011

My first query with CTE ( common table expression )



with curOrd (order_id, name, value,created)
as
(
select order_id,name,value,created
from ec_business_order_attributes
where order_id = '48117'
),
 ord (order_id, name, value,created)
as
(
select order_id,name,value,created
from curOrd
where and name ='kth_action_code' and [VALUE]='000'
)
select *,
(select top 1 a.value  from curOrd a
where
a.name ='subtotal'
order by
cast (a.created as float) - cast(( select ord.created from ord)  as float)
asc ) as [CCAmount]
from ord