从复杂的选择创建视图

时间:2010-01-09 13:50:02

标签: sql postgresql subquery

我有一个非常复杂的查询,我想从中创建一个视图。查询如下所示:

select s.avg as c3, fs.bayes, fs.sure, fs.visu, fs.fstd from 
(
SELECT  AVG(q.c3), COUNT(q.c3), q.std
FROM    (
        SELECT  std, c3, ROW_NUMBER() OVER (PARTITION BY std ORDER BY id) AS rn
        FROM    ssims
        WHERE   obraz = 'peppers2' and noisetype ='L' and data>'2009-12-23' and maska = 9
        ) q
WHERE   rn <= 15
GROUP BY
        std
        ) s
,(
SELECT  AVG(f.bayes) as bayes, AVG(f.sure) as sure, AVG(f.visu) as visu, COUNT(f.bayes) as fcount, f.std as fstd
FROM    (
        SELECT  std, bayes, sure, visu, ROW_NUMBER() OVER (PARTITION BY std ORDER BY id) AS rn
        FROM    falki_ssim
        WHERE   obraz = 'peppers2' and noisetype ='L'
        ) f
WHERE   rn <= 15
GROUP BY
        std
        ) fs
where s.std = fs.fstd

它选择具有指定参数的测试的平均结果。此查询的输出返回10行(标准值从5到50,步骤5,所以5,10,15 ......)和5列:c3,bayes,sure,visu,std

但我希望能够更改两个子查询的obraznoisetype字段。因此,在创建此类视图后,我希望能够以这种方式选择结果:

select * from my_view where obraz='peppers2' and noisetype = 'L'

怎么做?

1 个答案:

答案 0 :(得分:1)

我必须对其进行测试以获得正确的查询,但基本的想法是在您的选择查询中包含obraz和noisetype以及您的group by子句。像这样:

select s.obraz, s.noisetype, s.avg as c3, fs.bayes, fs.sure, fs.visu, fs.fstd from 
(
SELECT  obraz, noisetype, AVG(q.c3), COUNT(q.c3), q.std
FROM    (
        SELECT  obraz, noisetype, std, c3, ROW_NUMBER() OVER (PARTITION BY obraz, noisetype, std ORDER BY id) AS rn
        FROM    ssims
        WHERE   data>'2009-12-23' and maska = 9
        ) q
WHERE   rn <= 15
GROUP BY
        obraz, noisetype, std
        ) s
,(
SELECT  obraz, noisetype, AVG(f.bayes) as bayes, AVG(f.sure) as sure, AVG(f.visu) as visu, COUNT(f.bayes) as fcount, f.std as fstd
FROM    (
        SELECT  obraz, noisetype, std, bayes, sure, visu, ROW_NUMBER() OVER (PARTITION BY obraz, noisetype, std ORDER BY id) AS rn
        FROM    falki_ssim
        ) f
WHERE   rn <= 15
GROUP BY
        obraz, noisetype, std
        ) fs
where s.std = fs.fstd AND s.obraz = fs.obraz AND s.noisetype = fs.noisetype

您还应该使用JOIN关键字来连接表。