将临时表与联合查询组合在一起

时间:2014-04-17 22:34:26

标签: sql-server-2008

所以我有一个我正在研究的查询。它将按日期和单位类型包含发货,订单和退货数据。

我让每个子查询都工作,所以他们像这样聚集在一起:

Select dateproc,unit,totqty,type(ship)

union

Select dateproc,unit,totqty,type(order)

union

Select dateproc,unit,totqty,type(return)

现在不是每个日期都会包含一些内容,但我想表明该日期是否有任何日期,例如周末。

因此,同一个查询的代码可以创建一个名为#dates的临时表,其中包含已填充当月每一天的字段lookupdate

我需要使用此表加入组合的联合查询,以便我有一个月中每一天的记录。

1 个答案:

答案 0 :(得分:1)

如果对联合查询使用公用表表达式(CTE)并将其加入日期,则可能最容易阅读。

;WITH cte AS (

Select dateproc,unit,totqty,type(ship) type_total

union

Select dateproc,unit,totqty,type(order)

union

Select dateproc,unit,totqty,type(return)
)
SELECT * 
  FROM #dates a
       LEFT JOIN
       cte b ON a.date = b.dateproc