Bear with me, I'm SQL.stupid. I've finally learned that one should use views instead of crons when possible. Now, I have a view within a view question.

My stack friends have gotten me this far:

CREATE VIEW tbl.sums as SELECT 

table2.id, 

SUM( table1.column1 * 2 ) as column1Sum,

SUM( table1.column2 * 2 ) as column2Sum,

SUM( table1.column3 * 2 ) as column3Sum

FROM table1, table2
WHERE table1.table2_id = table2.id GROUP BY table2.id

I'd like to put in a 5th column into the view that's an equally-weighted rank of the other 3.

So, the equation would be something like (1/3)*percentile(column1Sum) + (1/3)*percentile(column2Sum) + (1/3)*percentile(column3Sum) where "percentile()" is the percentile rank of the column vs the rest of the column.

Please excuse the lack of clarity. This really isn't my specialty. Will edit as much as needed.

Thank-you very much in advance!

Percentile Clarity

In my case, percentile is the percentage rank from highest to lowest of a given column adjusted for repeats. So for a column with 100 values, the one with the largest, would be 100%, the one with the lowest would be 0% (or would it be 1%?). If there were 100 but 50 duplicates, the bottom two would share 2%.

有帮助吗?

解决方案

CREATE VIEW tbl.sums as SELECT 
    tmp.*,
    (1/3)*(tmp.column1Sum+tmp.column2Sum+tmp.column3Sum)
FROM (
    SELECT 
        table2.id, 
        SUM( table1.column1 * 2 ) as column1Sum,
        SUM( table1.column2 * 2 ) as column2Sum,
        SUM( table1.column3 * 2 ) as column3Sum
    FROM table1, table2
    WHERE table1.table2_id = table2.id GROUP BY table2.id
) AS tmp

The equation does not make much sense to me, I think there must be something wrong, or I didn't really get what the percentile is supposed to be... So I put just whatever, as long as it depends on the fields of the subquery.

If you hadn't used subqueries, but used instead column1Sum directly you would get an error about an unknown column.

Otherwise you could just rewrite the formula used to calculate the sums instead of using its name. But I guess this is not practical for your use case.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top