Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Field values from another table as column headers for query

$
0
0

I have the data below and would like the query results shown below also.  Basically I have a generic report table where there are three potential categories and three potential aggregated values from a separate data source.  I would like to run a query that returns the field descriptions as the column headers.  Hopefully my explanation is clear enough.  If there is an "almost gets  you there" solution then maybe I can take it and run with it, but I'm stumped at the moment.

Thanks!

-- create the tables

CREATE TABLE ReportData
(
ReportID INT,
Category1Value VARCHAR(20),
Category2Value VARCHAR(20),
Category3Value VARCHAR(20),
ValueField1Value INT,
ValueField2Value INT,
ValueField3Value INT
)

CREATE TABLE CategoryFields
(
ReportID INT,
CategoryID INT,
Description VARCHAR(20)
)

CREATE TABLE ValueFields
(
ReportID INT,
ValueFieldID INT,
Description VARCHAR(20)
)

-- insert some data

INSERT INTO ReportData (ReportID,
				    Category1Value,
				    Category2Value,
				    Category3Value,
				    ValueField1Value,
				    ValueField2Value,
				    ValueField3Value)
VALUES (1, 'Louisville', 'KY', '40245', 100, 200, 300)

INSERT INTO CategoryFields (ReportID,
					   CategoryID,
					   Description)
VALUES (1, 1, 'City')
INSERT INTO CategoryFields (ReportID,
					   CategoryID,
					   Description)
VALUES (1, 2, 'State')
INSERT INTO CategoryFields (ReportID,
					   CategoryID,
					   Description)
VALUES (1, 3, 'ZIP')

INSERT INTO ValueFields (ReportID,
					ValueFieldID,
					Description)
VALUES (1, 1, 'Total Units')
INSERT INTO ValueFields (ReportID,
					ValueFieldID,
					Description)
VALUES (1, 2, 'Average Units')
INSERT INTO ValueFields (ReportID,
					ValueFieldID,
					Description)
VALUES (1, 3, 'Max Units')

-- desired results
ReportID		 City	   State		ZIP		  Total Units	   Average Units	   Max Units
1			 Louisville  KY		40245	  100		   200			   300
Also, if a particular ReportID does not have a CategoryID #3 (meaning the three values are grouped only by 2 fields rather than three) I would love to be able to account for that.  For instance if there were only City and State, not ZIP, above then how to report that also.


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>