I have a table that stores various clients I have done work for, separated by Government and Commercial columns. The problem is that there could be an uneven number of clients in either column. When I do a SELECT, I end up with NULL values in irregular places because I can't think of a clean way to order the result set. For example, the following is possible with a straight SELECT (no ORDER BY):
Government | Commercial DOD | IBM DOS | Microsoft | Novell DVA | Oracle
As you can see, there is a NULL value in the Government column because there are more commercial clients than government. This could change at any time and there's no guarantee which column will have more values. To eliminate rendering with a blank value in the middle of a result set, I decided to perform two separate SELECTs into table variables (one for the Government clients and another for the Commercial) and then SELECT one final time, joining them back together:
DECLARE @Government TABLE
(
Row int,
PortfolioHistoryId uniqueidentifier,
Government varchar(40),
GovernmentPortfolioContentId uniqueidentifier
)
DECLARE @Commercial TABLE
(
Row int,
PortfolioHistoryId uniqueidentifier,
Commercial varchar(40),
CommercialPortfolioContentId uniqueidentifier
)
INSERT INTO @Government
SELECT
(ROW_NUMBER() OVER (ORDER BY Government)) AS Row,
PortfolioHistoryId,
Government,
GovernmentPortfolioContentId
FROM dbo.PortfolioHistory
WHERE Government IS NOT NULL
INSERT INTO @Commercial
SELECT
(ROW_NUMBER() OVER (ORDER BY Commercial)) AS Row,
PortfolioHistoryId,
Commercial,
CommercialPortfolioContentId
FROM dbo.PortfolioHistory
WHERE Commercial IS NOT NULL
SELECT
g.Government,
c.Commercial,
g.GovernmentPortfolioContentId,
c.CommercialPortfolioContentId
FROM @Government AS g
FULL OUTER JOIN @Commercial AS c ON c.Row = g.Row
I'm not necessarily unhappy with this query (maybe I should be), but is there a cleaner way to implement this?