以下の文は、入れ子になった順序付き分析機能とHAVING句を使用して、20以上の店舗で利益率が上位1パーセントに含まれる品目を検索します。
SELECT item, COUNT(store) FROM (SELECT store,item,profit,QUANTILE(100,profit) AS percentile FROM (SELECT ds.store, it.item, SUM(sales)- COUNT(sales) * it.item_cost AS profit FROM daily_sales AS ds, items AS it WHERE ds.item = it.item GROUP BY ds.store, it.item, it.item_cost) AS item_profit GROUP BY store, item, profit QUALIFY percentile = 0) AS top_one_percent GROUP BY item HAVING COUNT(store) >= 20;
この問合わせの結果は、このようになります。
Item Count(Store) ---------------- ------------ Chilean sea bass 99 Mackerel 149 Tako 121 Herring 120 Salmon 143