Showing posts with label crosstab. Show all posts
Showing posts with label crosstab. Show all posts

Saturday, October 15, 2011

Executing Postgres crosstab query as a prepared statement


I was executing a crosstab query as a prepared statement in Java(in a GWT app) and getting the following error -

PSQLException - Can't use query methods that take a query string on a PreparedStatement.

With some helpful folks from stackflow, I was able to resolve the error with the following code -

String query = "SELECT * FROM crosstab(
                      'SELECT rowid, a_name, value
                       FROM test WHERE a_name = ''att2''
                                    OR a_name = ''att3''
                      ORDER BY 1,2'
) AS ct(row_name text, cat_1 text, cat_2 text, cat_3 text);";

PreparedStatement stat = conn.prepareStatement(query);
ResultSet rs = stat.getResultSet();

//Note that, it is executeQuery() and not executeQuery(query)
stat.executeQuery();
rs = stat.getResultSet();
while (rs.next()) {
    //TODO
}





Thanks!

PostgreSQL crosstab query - Rotate a table about a pivot

An interesting feature of relational databases(postgres in this case) is the ability to rotate the table about a pivot. So if you have data like this-
 id | rowid | key | value
---+------+----+-------
  1 | test1 | key1      | val1
  2 | test1 | key2      | val2
  3 | test1 | key3      | val3
  4 | test1 | key4      | val4
  5 | test2 | key1      | val5
  6 | test2 | key2      | val6
  7 | test2 | key3      | val7
  8 | test2 | key4      | val8

And want to have a result set like this -

rowid | key1 | key2 | key3 | key4
------+------+-----+-----+------
 test1  | val1  | val2  | val3  | val4
 test2  | val5  | val6  | val7  | val8


It can be achieved by a "crosstab" query in a postgres database -



Update: 02/14/2013
The following can be achieved by a crosstab and also by an interesting SQL which I came across here - http://stackoverflow.com/questions/14863985/postgres-crosstab-maybe