sql >> データベース >  >> RDS >> PostgreSQL

複雑なクエリで順序付けられたシーケンスランクを生成する

    row_number()を2倍にするのはどうですか?

    with enchilada as (
    SELECT firstname,lastname,personid,year,(SELECT COALESCE(SUM(thevalue),0)
    FROM assets WHERE personidref = w.personid) AS assets ,
    (SELECT COALESCE(SUM(amount),0) FROM liabilities WHERE personidref = w.personid AND year = w.year) AS liabilities,
    ((SELECT COALESCE(SUM(thevalue),0) FROM assets WHERE personidref = w.personid AND year = w.year) - (SELECT COALESCE(SUM(amount),0) FROM liabilities WHERE personidref = w.personid AND year = w.year)) as worth,
    row_number() over(ORDER BY w.worth) as rank
    FROM members w
    WHERE year = 2012
    ORDER BY worth DESC LIMIT 2 )
    select row_number() over (order by rank) as new_rank, * from enchilada;
    


    1. UTC_DATEの例– MySQL

    2. YIIではフィールドリストの列「id」があいまいです

    3. 列のサブストリングにインデックスを作成するにはどうすればよいですか?

    4. 最も人気のあるカテゴリを見つけるためのSQL