Solved

Follow-up question, Dynamic PIVOT query

Posted on 2014-09-11
6
181 Views
Last Modified: 2014-09-11
Previous question here.

In the previous question, I forgot to mention that my production table was not exactly as listed because I assumed I could make the modifications I needed to the final query to pass in an additional variable @Product (values of 'Gas', 'Oil', 'Water') and select the appropriate column using a Case statement.  So, the following query works.
SET DATEFORMAT mdy;

Declare @Product nvarchar(5)
Declare @StartDate datetime2
Declare @EndDate datetime2
SET @Product = 'Gas'
Set @StartDate = '2014-09-01'
SET @EndDate = '2014-09-30'

--Define the string of dates to use in the Pivot clause
DECLARE @docDatesTable TABLE
(
	[docDate] Datetime
);

INSERT INTO @docDatesTable
SELECT DISTINCT docDate FROM tbl_sysProduction
WHERE docDate >= @StartDate AND docDate < DATEADD(day, 1, @EndDate);

--Build the String containing the date values to be used in the pivot
DECLARE @docDates VARCHAR(MAX);
SELECT @docDates = COALESCE(@docDates + '],[', '') +
		  (LEFT(CONVERT(VARCHAR, [docDate], 101),6) + RIGHT(YEAR([docDate]),2))
FROM @docDatesTable ORDER BY [docDate]

--Build the dynamic SQL String
DECLARE @sql NVARCHAR(MAX);
SET @sql = 'SELECT * FROM (
SELECT IsNull(W.Bolo_ID, F.Bolo_ID) as Bolo_ID
, IsNull(W.Common_Name, F.Facility_Name) as Well_Facility
, P.[Entity_ID]
, P.[docDate]
, Volume = [Gas] 
FROM tbl_sysProduction as P
LEFT JOIN tbl_sysWells as W ON P.Entity_ID = W.Entity_ID
LEFT JOIN tbl_sysFacilities as F on P.Entity_ID = F.Entity_ID
) AS [SubTable]
PIVOT
(
     SUM([Volume])
FOR [docDate] IN ([' + @docDates + '])
) AS [Pivot]
ORDER BY Bolo_ID, Well_Facility;
';

EXEC sp_executesql @sql;

Open in new window

But when I replace this line:
, Volume = [Gas]

Open in new window

with:
, Volume = CASE WHEN ' + @Product + ' = ''Gas'' THEN [Gas]
                WHEN ' + @Product + '= ''Oil'' THEN [Oil]
                WHEN ' + @Product + '= ''Water'' THEN [Water]
                ELSE NULL END

Open in new window

I get an error message:
Msg 8114, Level 16, State 5, Line1
Error converting data type varchar to float

I also tried it with:
, Volume = CASE WHEN @Product = ''Gas'' THEN [Gas]
                WHEN @Product = ''Oil'' THEN [Oil]
                WHEN @Product = ''Water'' THEN [Water]
                ELSE NULL END

Open in new window

but that raised an error also:
Must declare variable "@Product"

So, the question is, how do I pass in a value for the Product (@Product) and retrieve the correct column from tbl_sysProduction based on that value in the dynamic SQL Statement?
0
Comment
Question by:Dale Fye (Access MVP)
  • 4
  • 2
6 Comments
 
LVL 2

Expert Comment

by:Sytech Solutions
ID: 40317982
Hi Dale

Do you mind posting the design of the table so I can see what the data types for the Gas, Oil and Water columns are?

Thanks
0
 
LVL 2

Accepted Solution

by:
Sytech Solutions earned 500 total points
ID: 40318023
Bit of a stab in the dark without the tables but try this:

SET @sql = 'SELECT * FROM (
SELECT IsNull(W.Bolo_ID, F.Bolo_ID) as Bolo_ID
, IsNull(W.Common_Name, F.Facility_Name) as Well_Facility
, P.[Entity_ID]
, P.[docDate]
, Volume = CASE ''' + @Product + ''' WHEN ''Gas'' THEN [Gas]
                WHEN  ''Oil'' THEN [Oil]
                WHEN ''Water'' THEN [Water]
                ELSE NULL END
FROM tbl_sysProduction as P
LEFT JOIN tbl_sysWells as W ON P.Entity_ID = W.Entity_ID
LEFT JOIN tbl_sysFacilities as F on P.Entity_ID = F.Entity_ID
) AS [SubTable]
PIVOT
(
     SUM([Volume])
FOR [docDate] IN ([' + @docDates + '])
) AS [Pivot]
ORDER BY Bolo_ID, Well_Facility;
';

Open in new window


Thanks
0
 
LVL 47

Author Comment

by:Dale Fye (Access MVP)
ID: 40318024
And your name is?

CREATE TABLE [dbo].[tbl_sysProduction](
	[Prod_ID] [int] IDENTITY(1,1) NOT NULL,
	[Entity_ID] [int] NOT NULL,
	[docDate] [datetime] NOT NULL,
	[Oil] [float] NULL,
	[Gas] [float] NULL,
	[Water] [float] NULL,
	[TimeStamp] [timestamp] NOT NULL,
 CONSTRAINT [PK_tbl_sysProduction] PRIMARY KEY CLUSTERED 
(
	[Prod_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Open in new window

Although I've accessed data from SQL Server a lot in the past, I've only recently really started building my own, so selection of float may have been the wrong datatype to emulate a double in Access.
0
Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

 
LVL 2

Expert Comment

by:Sytech Solutions
ID: 40318031
it's Ben. Float is correct for a double.

Thanks
0
 
LVL 47

Author Closing Comment

by:Dale Fye (Access MVP)
ID: 40318039
That took care of it.  I should have done a SELECT on the value of @SQL before trying to execute it and it would have been obvious.
0
 
LVL 2

Expert Comment

by:Sytech Solutions
ID: 40318041
Yay excellent.
0

Featured Post

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how the fundamental information of how to create a table.

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now