12.09.2008

A Monster Of An SQL Query

So i'm in the middle of working on a web project. At some point I'll be switching over to using home brewed blogging software on my main website and I'll eventually figure out how to cross-post to here or something. Whatever.

My point is that I've been sharpening up my SQL skills. Today, over the course of about five hours I taught myself how to make the following SQL query. What does this sucker do? It let's me take three different tables from my database, grab values from all of them and then sum up some of them but not others.

What's the context? It's the main query I needed to figure out how to write in order to get the Leaderboard for S.Rex War to work the way I envisioned. Yes that's a rather mysterious comment. If I had coded up the blog-lite software I could be blogging this as I go along. Maybe I'll do that tomorrow. It shouldn't take me very long at all to do.

SELECT FullName, Wins, Losses, Games, (Wins/Games) AS Ratio, UserJoinDate FROM (SELECT CONCAT(User.FirstName, " ", User.LastName) AS FullName, SUM(IF(STRCMP(Game.GameStatus,'1'), 0, 1)) AS Wins, SUM(IF(STRCMP(Game.GameStatus,'2'), 0, 1)) AS Losses, SUM(1) AS Games, UserAction.ActionDate As UserJoinDate FROM User INNER JOIN Game ON User.UserKey=Game.UserKey INNER JOIN UserAction ON User.UserKey=UserAction.UserKey WHERE UserAction.ActionType='Create' GROUP BY User.UserKey) AS LeaderBoard