Let's say I have a hypothetical table like so that records when some player in some game scores a point:
name points
------------
bob 10
mike 03
mike 04
bob 06
How would I get the sum of each player's scores and display them side by side in one query?
Total Points Table
bob mike
16 07
My (pseudo)-query is:
SELECT sum(points) as "Bob" WHERE name="bob",
sum(points) as "Mike" WHERE name="mike"
FROM score_table
In pure sql:
This neat solution works because of mysql's booleans evaluating as
1
fortrue
and0
forfalse
, allowing you to multiply truth of a test with a numeric column. I've used it lots of times for "pivots" and I like the brevity.You can pivot your data 'manually':
but this will not work if the list of your players is dynamic.
Or for the pivot
you can use pivot function also for the same thing .. even by performance vise it is better option to use pivot for pivoting... (i am talking about oracle database)..
you can use following query for this as well.. -- (if you have only these two column in you table then it will be good to see output else for other additional column you will get null values)
in this query you will get data very fast and you have to add or remove player name only one place
:)
if you have more then these two column in your table then you can use following query
Are the player names all known up front? If so, you can do:
If you don't, you still might be able to use the same method, but you'd probably have to build the query dynamically. Basically, you'd
SELECT DISTINCT name ...
, then use that result set to build each of theCASE
statements, then execute the result SQL.This is called pivoting the table: