views:

47

answers:

1

Hi, I have quite complicated query from which I would like to create a view. The query looks like this:

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

It selects me averaged results of the tests with specified parameters. The output of this query returns 10 rows (std values from 5 to 50 with step 5, so 5, 10, 15...) and 5 columns: c3, bayes, sure, visu, std

But I would like to be able to change the obraz and noisetype field for both sub-queries. So after creating such view I would like to be able to select results in this way:

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

How to do it?

+1  A: 

I'll have to test it to get the exact query right, but the basic idea is to include obraz and noisetype in your select queries and your group by clauses. Something like this:

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

You should also the JOIN keyword to join tables.

Mark Byers
Firstly, obraz and noisetype must be present at every level of select. There are in fact 3 levels of selections. And even after correcting it, the query Unfortunately is not working as i would expect (it selects only one combination of obraz/noisetype of all available
Gacek
I found one error: the partition by in the row_number also needs to include obraz and noisetype. This is fixed in two places.
Mark Byers
yes, now it works perfectly, thank you!
Gacek