lundi 21 décembre 2015

How can I add "row position" to a query with a SUM(…) column from subquery?

I am getting a weird error when I try to get SUM(…) column in a subquery and then get row "indexes":

WITH lb(displayName, val) AS (
    SELECT user.displayName, SUM(stats.weight) AS val FROM stats
    LEFT OUTER JOIN user ON user.id = stats.userId
    GROUP BY user.id
    ORDER BY val DESC
)
SELECT displayName, val, (SELECT COUNT(*) FROM lb b WHERE a.val <= b.val) AS position FROM lb a

The error I get when I run it in SQLiteBrowser is: misuse of aggregate: SUM(): followed by the full text of the query.

However, the query works fine if I either:

  • remove the , (SELECT COUNT(*) FROM lb b WHERE a.val <= b.val) AS position from the final SELECT;
  • do not use SUM.

(but I do need both)

Here is the (working) example (sqlfiddle), where the row index is missing (it also includes some test data): http://ift.tt/1TbS2Or

How can I fix it, so it would work (that means, add row numbers to the result set)?

I need these indexes because I'm going to add a WHERE clause after this query, and I need to know the order of the rows which were retained.

For example, the wanted result for the test data in the fiddle above is:

| displayName |  val | position |
|-------------|------|----------|
|       name2 | 1256 |        1 |
|       name4 |  133 |        2 |
|       name5 |   62 |        3 |
|       name3 |   43 |        4 |

(position could as well start with 0, it's not important)

P.S. replacing the SQL implementation (SQLite) with something else is not an option (at least not right now)

Aucun commentaire:

Enregistrer un commentaire