What if you want to PIVOT against a text column?

If you’ve ever worked with or researched SQL Server’s PIVOT function, you probably noticed most of the samples pivot against an id column.  Typically an int column like EmployeeID, or StoreID.  That’s fine and dandy, but what happens when you want to PIVOT against a varchar column?  If you’ve been in this need you know this is a bit of a task.

I had this need on an app recently and built a little dynamic sql action that does just this.  The example below however, uses the the DatabaseLog table in the AdventureWorks sample database to return a count of Events logged for each Schema.  Before jumping into the PIVOT, here’s a simple query that gives you the same information, all Schemas, Events, and Event counts.

SELECT      [Schema], [Event], COUNT( [Event] ) AS 'event_count'
FROM        DatabaseLog
GROUP BY    [Schema], [Event]
ORDER BY    [Schema]

Running this query should give you a long result looking something like this.

Data is there, format isn't nice like PIVOT

While this query returns the same information to you, I don’t like this format as much as using PIVOT.  This query result is long and requires a bit of manipulation to get into a readable format.

Now let’s have a look at retrieving the same information using the PIVOT function.

/*
Example of a dynamic PIVOT against a varchar column from the Adventureworks database

References :
PIVOT & UNPIVOT function

http://msdn.microsoft.com/en-us/library/ms177410.aspx

AdventureWorks sample Databases

http://msdn.microsoft.com/en-us/library/ms124501(v=SQL.100).aspx

AdventreWorks.DatabaseLog

http://msdn.microsoft.com/en-us/library/ms124872.aspx

*/

USE AdventureWorks

-- populate temp Event table
SELECT DISTINCT [Event] as 'Event'
INTO	#events
FROM	DatabaseLog

-- this var will hold a comma delimited list of [Event]
DECLARE	@eventList nvarchar(max)

-- create a flattened [Event], list for the PIVOT statement
SELECT	@eventList = COALESCE( @eventList + ', ', '') + CAST( QUOTENAME( [Event] ) AS VARCHAR(1000) )
FROM	#events
ORDER BY [Event]

-- drop table var since our data now lives in @eventList
DROP TABLE #events

-- this var will hold the dynamic PIVOT sql
DECLARE @pvt_sql nvarchar(max)

-- NOTE : we're using dynamic sql here because PIVOT
-- does not support sub SELECT in the 'FOR Event IN ( )'
-- part of the query.
-- If we don't use dynamic SQL here, the PIVOT function
-- requires you to hard code each 'Event'
-- Using SELECT * here so the [Event] columns are auto included
SET @pvt_sql = 'SELECT	*
                FROM
                (
                    SELECT	[Event], [Schema]
                    FROM	DatabaseLog
                ) AS data
                PIVOT
                (
                    COUNT( Event )
                    FOR Event IN
                    ( ' + @eventList + ' )
                ) AS pvt'

-- run the query
EXEC sp_executesql @pvt_sql

Assuming you have the AdventureWorks database installed on your server, running this sql should give you a result looking something like this.

Dynamic PIVOT on text column Event

Show all Schemas and count of each Event type

This query result was truncated to fit in this post, but just know the query above creates a column for every Event in the Databaselog table.

A quick explanation of what’s happening in this sql

  1. First you fill a table variable ( #events ) with all Events from DatabaseLog
  2. Next create a comma delimited list of the Events inside of the table variable
  3. Drop the table variable now that we’ve got our delimited list of Events
  4. Build the PIVOT statement as a string so you can inject the Events list
  5. Fire the dynamic SQL via EXEC

Dynamic SQL is something that comes in handy from time to time, but I do my best to only use it if I absolutely have to.  In this case we’re using it because the PIVOT function does not allow sub SELECT statements.  This is also why we create a specially formatted delimited list of Events prior to building the dynamic sql.

So there you have it, one example of using PIVOT against a varchar column instead of an integer column.  Also, this is a pretty good example of a dynamic PIVOT since it’s pretty simple.  I hope this makes sense, and if you have any suggestions of better techniques, I’d love to hear it.

Weird, that bat file path doesn’t jive from the toolbar

I just noticed something when running some batch files on Windows 7. If I launch the file from Windows Explorer, the path in the command window matches the location of the batch file.

Bat file path and cmd paths match when you double click it

The paths, they match!

However, I typically launch my batch files from a toolbar on my taskbar that points to the same folder.  The batch file still works, but the path shown in the command window is weird.  I have no idea how an Adobe Version Cue path could get injected, but it does.

Launching a bat from a toolbar injects a path to Adobe Version Cue?

Weird paths

To capture both shots of the command window I had to hit Pause.  These aren’t faked, they’re just completely random.

How would you like some TV with that soup.io?

I often forget about soup.io‘s TV feature.  This is one of the coolest features I’ve seen on today’s modern social – micro blog – services.  It’s a TV station built out of videos you’ve tweeted or posted to your soup.io account.  Here is my soup.io / TV station.


Click image to launch http://ericfickes.soup.io/tv


DataBind a List of custom classes to an ASP:ListBox control

Recently I was scratching my head at this error from the .NET Framework

DataBinding: ‘MyApp.vo.customVO’ does not contain a property with the name ‘Name’

I was stumped because my custom VO class did in fact have a public property called Name.  After many trials and tribulations I figured out that .NET didn’t like how I structured my custom class.

Here is what my original custom class looked like.

namespace MyApp.vo
{
    public class customVO
    {
        public Int32 id  = 0;
        public DateTime time  = new DateTime();
        public string Name  = string.Empty;
        public string DeviceType  = string.Empty;
        public string ObjectIDs  = string.Empty;
    }
}

Luckily I have JetBrains ReSharper installed, and it suggested using C#’s Auto-Implemented properties. This is the one thing I hadn’t thought about trying, and it ended up being the fix! My new custom VO class now looks like this.

namespace MyApp.vo
{
    public class customVO
    {
        public Int32 id { get; set; }
        public DateTime time { get; set; }
        public string DeviceType { get; set; }
        public string ObjectIDs { get; set; }
        public string Name { get; set; }
    }
}

So if you find yourself running into this error while trying to DataBind a collection of custom classes to a ListBox or similar control, have a look at your custom class and see if you can convert it over to using auto-implement properties as well.

Now I’m not suggesting this is the only way to DataBind a List of custom classes to a ListBox, but it solved my problem and let me do direct databinding from my service call without having to do any pre-processing on my list.

Hope this helps someone else.

Incorrect syntax near the keyword ‘table’ in TSQL

Ran into something little that I know I’m going to forget if I don’t write down. It appears that when using a TABLE variable in tsql ( SQL Server 2005 ), you must DECLARE that variable on it’s own line, as opposed to inline with your other @variables.

Typically in my sprocs or sql scripts I do my best to have a main DECLARE block and seperate my @variables with a comma like this.

Typically I DECLARE=

If you're using a TABLE variable, put it on it's own DECLARE line

After some mucking around, it turns out moving the TABLE @variable to it’s own DECLARE line fixes this issue.

DECLARE TABLE @variables on their own line

DECLARE TABLE @variables on their own line

I haven’t found this info in SQL BOL, so I hope this helps somebody else.