在SQL查询中加入Union联合杀死性能

时间:2017-03-07 17:32:46

标签: sql sql-server performance query-performance

有没有办法改进以下查询?

以下查询提供了正确的结果,但却影响了性能。

2 个答案:

答案 0 :(得分:2)

也许是这样的?

Select 
  ID,
  max(case when MYDATE = '20160105 10:00:00' then PRICE else 0 end),
  max(case when MYDATE = '20140805 10:00:00' then PRICE else 0 end),
  max(case when MYDATE = '20170215 10:00:00' then PRICE else 0 end)
FROM
(
  select ID, PRICE FROM TABLE1 WHERE MYDATE in ('20160105 10:00:00', '20140805 10:00:00', '20170215 10:00:00')
  UNION ALL
  SELECT ID, PRICE FROM TABLE2 WHERE MYDATE in ('20160105 10:00:00', '20140805 10:00:00', '20170215 10:00:00')
) A
group by ID

如果您提供任何示例,猜测会更容易......

答案 1 :(得分:0)

你可以避免使用(),使用A.ID进行连接,这可以为性能带来一些好处

Select A.ID, A.[2016 Price], B.[2014 Price], C.[2017 Price]
FROM

  (
  select ID, PRICE [2016 Price] FROM TABLE1 WHERE MYDATE = 2016-01-05 10:00:00
  UNION
  SELECT ID, PRICE FROM TABLE2 WHERE MYDATE = 2016-01-05 10:00:00
  ) A 

INNER JOIN

  (
  select ID, PRICE [2014 Price] FROM TABLE1 WHERE MYDATE = 2014-08-05 10:00:00
  UNION
  SELECT ID, PRICE FROM TABLE2 WHERE MYDATE = 2014-08-05 10:00:00
  ) B ON A.ID =B.ID

INNER JOIN

  (
  select ID, PRICE [2017 Price] FROM TABLE1 WHERE MYDATE = 2017-02-15 10:00:00
  UNION
  SELECT ID, PRICE FROM TABLE2 WHERE MYDATE = 2017-02-15 10:00:00
  )  ON A.ID =C.ID