如何合并 - 联合排序数据集而不进行其他排序

时间:2017-03-28 23:59:29

标签: sql-server sql-server-2014

我试图为下游流程获取有效的数据Feed,但生成的查询计划尝试在传递任何内容之前缓存整个输出。

我的输入数据是一个包含以下内容的表:

ID,Attribute1,Attribute2,Attribute3,otherID
- Clustered index on ID(not unique) 
- OtherID is unique)

about 10M rows, output query has up to 50 rows per ID, but 7 is typical

有一些辅助表,每个otherID包含0-5个属性,结构类似

Attribute4Table:
id4(PK),OtherID, Attribute4 

Attribute5Table:
id5(PK),OtherID, Attribute5 

,所需的输出是:

ID Dimension Value
4 'Attribute1' w
4 'Attribute4' x
4 'Attribute4' y
4 'Attribute3' z
5 'Attribute2' a
5 'Attribute3' b
5 'Attribute1' c

按当前查询看起来像:     ## quoteHistory(id)

上有一个聚簇索引
select * from ( 
select ID,  'Attribute1' Dimension, cast(thing1 as varchar(400)) Value from ##quoteHistory
  UNION  ALL 
select  ID,  'Attribute2' Dimension, cast(thing2 as varchar(400)) Value from ##quoteHistory
  UNION ALL
... couple of other similer clauses, 'Dimension' is unique
) x order by ID   where Value is not null

输出要求:给定ID的所有行一起输出(下游应用程序按ID组使用数据ID组,处理此数据的成本远远超过查询)。

问题:当它(正确)检测到它可以使用合并联合时,sql server会不必要地预先排序数据..

query plan including value

由"不必要的"如果你删除"值"从查询中获得我期待的查询计划,这是一个没有阻塞组件的流输出:

select * from ( 
    select ID,  'Attribute1' Dimension from ##quoteHistory
      UNION  ALL 
    select  ID,  'Attribute2' Dimension from ##quoteHistory
      UNION ALL
    ... couple of other similer clauses
) x order by ID 

query plan selecting ID and Dimension only

问题: 如何强制生成第二个计划的第一个查询,因为该计划确实产生了我感兴趣的输出排序。

编辑: 在完整数据集中,其他表有时会以1:多的关系连接到## quoteHistory,以获取该维度的多个值。

0 个答案:

没有答案
相关问题