Question: I would like to select the top 1% of rows; however, I cannot use subqueries to do it. I.e., this won't work:

```
SELECT * FROM mytbl
WHERE var='value'
ORDER BY id,random()
LIMIT(SELECT (COUNT(*) * 0.01)::integer FROM mytbl)

```

How would I accomplish the same output without using a subquery with limit?

Answer: 
You can utilize [`PERCENT_RANK`](http://www.postgresql.org/docs/current/static/functions-window.html):

```
WITH cte(ID, var, pc) AS
(
  SELECT ID, var, PERCENT_RANK() OVER (ORDER BY random()) AS pc
  FROM mytbl
  WHERE var = 'value'
)
SELECT *
FROM cte
WHERE pc <= 0.01
ORDER BY id;

```

`**[`SqlFiddleDemo`](http://sqlfiddle.com/#!15/1ede2/3/0)**`
If I got it right, you need:

1. Random 1% sample of all rows,
2. If some `id` is within the sample, all rows with the same `id` must be there too.

The follow sql should do the trick:

```
with ids as (
    select   id,
             total,
             sum(cnt) over (order by max(rnd)) running_total
    from     (
               select id,
                      count(*) over (partition by id) cnt,
                      count(*) over () total,
                      row_number() over(order by random()) rnd
               from   mytbl
             ) q
    group by id,
             cnt,
             total
)
select   mytbl.*
from     mytbl,
         ids
where    mytbl.id = ids.id
and      ids.running_total <= ids.total * 0.01
order by mytbl.id;

```