将View中的WHERE子句传播到子查询

时间:2014-01-06 15:34:36

标签: sql sql-server tsql

我必须在视图中转换此查询:

SELECT col1,
       CONVERT(decimal(5, 4), SUM(Volume) / CONVERT(float, (
                                        SELECT SUM(Volume) 
                                        FROM A INNER JOIN B ON [..]
                                        WHERE A.CodA = @param1 AND CodB.[Year] = @param2))
        ) AS [VolPercent]
FROM A INNER JOIN B ON [..]
WHERE A.CodA = @param1 AND CodB.[Year] = @param2

因此,我必须使用外部查询中的相同clausule过滤子查询 会是这样的:

SELECT col1,
       CONVERT(decimal(5, 4), SUM(Volume) / CONVERT(float, (
                                        SELECT SUM(Volume) 
                                        FROM A as C INNER JOIN B as D ON [..]
                                        WHERE C.CodA = A.CodA AND D.[Year] = B.[Year]))
        ) AS [VolPercent]
FROM A INNER JOIN B ON [..]

我该怎么做?有办法吗?

1 个答案:

答案 0 :(得分:1)

创建一个没有WHERE的视图,然后使用WHERE子句查询View应该得到完全相同的性能完全相同的结果。但是,您需要添加将在where子句中使用的列。所以是的,创建您的视图

create view MyView as
SELECT ACod.A, CodB.[Year],
       col1,
       CONVERT(decimal(5, 4), SUM(Volume) / CONVERT(float, (
                                        SELECT SUM(Volume) 
                                        FROM A as C INNER JOIN B as D ON [..]
                                        WHERE C.CodA = A.CodA AND D.[Year] = B.[Year]))
        ) AS [VolPercent]
FROM A INNER JOIN B ON [..]

然后您的查询是:

select * from MyView
where A = whatever
and [Year] = whatever

干杯 -