t-sql 随记

with _t as(select i.id,i.name,
case
when (i.InAmountTotal - i.OutAmountTotal) > 0 and (i.InCostTotal - i.OutCostTotal) > 0
then convert(numeric(18,4),(i.InCostTotal - i.OutCostTotal) / (i.InAmountTotal - i.OutAmountTotal+1))
else 0 end as salepriceavg,

case when i.incost<=0 or i.incost is null then 0 else i.incost end as incost,count(s.id) as totalcount
from dbo.ExtendCDKItem as i
left join [ExtendCDKItemStore] as s
on s.itemid=i.id
where 1=1
 and 1&i.flag<>1 group by i.id,i.name,i.incost,i.incosttotal,i.outcosttotal,i.inamounttotal,i.outamounttotal)
select *,(select count(id) from ExtendCDKItemStore as s where s.itemid=_t.id and
1&s.flag<>1 and 2&s.flag<>2 and
(s.saleorderid is null or s.saleorderid='')) as normal,(select sum(oi.amount)
from dbo.ExtendCDKSaleOrderItem as oi left join dbo.ExtendCDKSaleOrder as o on o.id=oi.orderid
where oi.itemid=_t.id and 1&o.flag<>1 and 2&o.flag<>2
and 1&oi.flag<>1) as waitingsend,(select count(id) from ExtendCDKItemStore as
s where s.itemid=_t.id and 1&s.flag<>1 and 2&s.flag=2
and (s.saleorderid is null or s.saleorderid='')) as problem,(select count(id) from ExtendCDKItemStore as s
where s.itemid=_t.id and 1&s.flag=1) as invalid,(select count(id)
from ExtendCDKItemStore as s where s.itemid=_t.id and 1&s.flag<>1
and 2&s.flag<>2 and (s.saleorderid is not null and s.saleorderid<>''))
as saled from _t

你可能感兴趣的:(t-sql 随记)