SQL 服务器:当从相同 table 和不同 table 获取日期时,使用其他东西而不是联合

SQL Server : use other thing instead of union when date fetch from same table and different table

我使用 union 合并来自 table 的 selected 数据。所有数据 select 来自相同的 table 但在每个 select 中,查询 select 一些不同的列。

Table 架构:

   EID     name      x1       x2       x3
--------|--------|--------|--------|--------
   int    string   float    float    float

示例数据:

样本bl

  EID   name    x1     x2     x3
------|------|------|------|------
  110   Tom     2      3      5
  110   John    4      3      6
  110   Sam     1      2      3

查询:

select 
    name, 'x1' as title, x1 as result
from
    Sampletbl
where 
    EID = 110

union

select 
    name, 'x2' as title, x2 as result
from 
    Sampletbl
where 
    EID = 110

union

select 
    name, 'x3' as title, x3 as result
from
    Sampletbl
where 
    EID = 110

输出结果应如下所示:

 name   title   result  
------|-------|------
 Tom     x1      2      
 Tom     x1      3      
 Tom     x1      5      
 John    x2      4      
 John    x2      4      
 John    x2      6      
 Sam     x3      1      
 Sam     x3      2      
 Sam     x3      3      

问题:在不使用 unionunion all 的情况下获取数据是更好的方法吗?

使用的 DBMS 是 SQL Server 2008 R2,但我可以升级到 SQL Server 2014 或更新版本。

更新:

原始 table 有数百万行。每个 select 从 table 读取数据。 每行都是唯一的,每列都有数据。 (可空=假) 我想要提高性能的方法,但我无法更改结果的结构 select.

您可以尝试将 CROSS APPLYVALUES

一起使用
SELECT v.*
FROM T
CROSS APPLY (VALUES (name, 'x1',x1),
                    (name, 'x2',x2),
                    (name, 'x3',x3)
            ) 
            v (name, title,result )
order by title

[结果]:

|  name | title | result |
|-------|-------|--------|
|   Tom |    x1 |      2 |
| John  |    x1 |      4 |
|   Sam |    x1 |      1 |
|   Sam |    x2 |      2 |
| John  |    x2 |      3 |
|   Tom |    x2 |      3 |
|   Tom |    x3 |      5 |
| John  |    x3 |      6 |
|   Sam |    x3 |      3 |

sqlfiddle

叫做UNPIVOT:

declare @t table (EID int, name varchar(13), x1 float, x2 float, x3 float)
insert into @t(EID,name,x1,x2,x3) values
(110,'Tom ',2,3,5),
(110,'John',4,3,6),
(110,'Sam ',1,2,3)

select
    *
from
    @t
    unpivot (
        result for title in (x1,x2,x3)) u

结果:

EID         name          result                 title
----------- ------------- ---------------------- -----
110         Tom           2                      x1
110         Tom           3                      x2
110         Tom           5                      x3
110         John          4                      x1
110         John          3                      x2
110         John          6                      x3
110         Sam           1                      x1
110         Sam           2                      x2
110         Sam           3                      x3

如果您的所有输出行都将不同(从检查当前查询来看,我希望这是真的),那么对当前查询的转换也会更快、干扰更少 - 使用 UNION ALL 而不是 UNIONUNION 指定为删除重复项,如果您的输出包含大量行,这可能会占用处理时间的很大一部分。