这个SQL Server CTE可以用更简单的方式表达吗?基本查询?

时间:2016-01-21 17:48:05

标签: sql-server-2012

这样我可以将所有联合或加入某种更大的外部查询吗?

-- Get purchase order due date for first purchase order after today which completes a cumulative sum satisfying demand which currently exceeds inventory supply
with cte as 
(
    select
        t1.itemcode as itemcode, 
        t1.dscription as itemname, 
        t1.quantity as quantity, 
        (select sum(t6.quantity)
         from por1 t6
         inner join opor t7 on t6.docentry = t7.docentry
         where t7.docduedate <= t2.docduedate
           and t7.docduedate > getdate()
           and t6.itemcode = 'item001') as totalqty,
        t2.docduedate as eta
    from 
        por1 t1
    inner join 
        opor t2 on t1.docentry = t2.docentry
    where 
        t1.itemcode = 'item001'
        and t2.docduedate > getdate()
)
select 
    cte.itemcode, cte.itemname, 
    convert(char(10), min(cte.eta), 101)
from 
    cte
where 
    totalqty > 55  -- I don't want this to be literal, the outer join would supply this as a calculated value
group by 
    cte.itemcode, cte.itemname

重新查询外部查询(上面没有包含这项内容,因为我还没有能够将外部查询加入到cte中 - 我不知道你可以),我&#39; d喜欢从外部查询计算当前显示为55的金额,并根据外部查询中的过滤列表控制哪些项目代码返回,而不是仅选择一个文字项目代码(如上所述)。

我尝试使用having子句获取totalqty但没有成功。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您想获得TotalQty的结果,还是只想将其用作条件?

如果是前者,我会说CTE的方式是最好的。否则,我会将其重新组合为选择进入TotalQty的WHERE EXISTS子句,如WHERE EXISTS (SELECT SUM(T6.Quantity) [...] HAVING SUM(T6.Quantity) > 55)