Rails構文を使用してこれを作成する方法(PostgreSQL)?:
SELECT fld1, fld2
FROM
(
SELECT fld1, fld2, count(*) as cnt FROM data WHERE fld2 not in('exclude1', 'exclude2') GROUP BY fld1, fld2 ORDER BY COUNT(*) DESC LIMIT 100
UNION ALL
SELECT fld1, fld2, count(*) as cnt FROM data WHERE fld2 in('exclude1', 'exclude2') GROUP BY fld1, fld2
) x
ORDER BY x.cnt DESC
私は次のようにしました:
my_data = (Data.all(
:select => sel_clause,
:conditions => "data.fld2 not in %s" % [in_clause],
:group => grp_clause,
:order => 'count(*) desc',
:limit => @max_rows) <<
Data.all(
:select => sel_clause,
:conditions => "data.fld2 in %s" % [in_clause],
:group => grp_clause).order('cnt desc')
問題は、この << が従来の「UNION ALL」ではなく、2 つの配列の結合であり、結果の配列に「順序」を適用できないことです。