16

In SPARQL, we can group the rows by a column through the gollowing syntax:

GROUP BY ?colName

Can we group by more than 1 columns eg:

GROUP BY (?colName1 + ?colName2 + ?colName3) 

Suppose a query like:

Select ?a ?b ?c (MIN(?y) AS ?d)
Where {
....
}
GROUP BY (?a + ?b + ?c)

But this query does not work.

laxonline
  • 2,657
  • 1
  • 20
  • 37
sapthrishi007
  • 393
  • 3
  • 13

3 Answers3

9

You can GROUP BY multiple variables (not columns) by listing them with a space in between:

GROUP BY ?a ?b ?c
Ben Companjen
  • 1,417
  • 10
  • 24
8

In addition to Ben Companjen's answer of

GROUP BY ?a ?b ?c

you need to fix the SELECT line as you can't pass out the indeterminate non-group keys without explicitly saying so e.g.

SELECT (sample(?a) as ?A) (sample(?b) as ?B) (sample(?c) as ?C) (min(?y) as ?d)
serrulien
  • 695
  • 4
  • 14
AndyS
  • 16,345
  • 17
  • 21
  • I hadn't read about `SAMPLE` yet, but now that I did, I think the `SELECT` clause does not need to be fixed. `SAMPLE` is needed for variables in the `SELECT` clause that are _not_ in the `GROUP BY` clause and not aggregated otherwise, but `?a ?b ?c` are exactly the variables in the `GROUP BY` clause. If some additional variable `?e` were `SELECT`ed, but not `GROUP BY`ed, it would need to be `SAMPLE`d. – Ben Companjen Jan 23 '13 at 20:55
  • The variables in `SELECT` and in `GROUP BY` just need to be in the same exact order, `SELECT` then as one or few more variables, to show the sums, etc. – Hugolpz Feb 07 '23 at 07:20
-6

Have you tried something like

SELECT ?a+b+?c, (MIN(?y) AS ?d) Where { .... } GROUP BY (?a+?b+?c)

This works in SQL Server just fine

Imtiaz
  • 11
  • 1