Pivoting Issue (what am I missing)? - sql

Trying to pivot data and add a calculated column to no avail.
I have tried the enclosed code below but cannot get exactly what I am after.
My table consists of three columns
TABLE_NAME, REPORT_DATE, COUNT_ROWS
For the last two [REPORT_DATE]s, I am trying to show in a pivot the [COUNT_ROWS] for each [TABLE_NAME]
What am I missing? Additionally, how would I go about adding a column subtracting the values between the two dates in the pivot?
DECLARE #cols AS NVARCHAR(MAX)='';
DECLARE #query AS NVARCHAR(MAX)='';
SELECT #cols = #cols + QUOTENAME(REPORT_DATE) + ',' FROM (select DISTINCT TOP 2 REPORT_DATE from account_report order by REPORT_DATE desc) as tmp
select #cols = substring(#cols, 0, len(#cols)) --trim "," at end
set #query =
'SELECT * from
(select [TABLE_NAME], [COUNT_ROWS] from account_report
) src
pivot
(sum([COUNT_ROWS]) for [TABLE_NAME] in (' + #cols + ')
) piv'
execute(#query)
All I am getting from the script is a two column result of the two [REPORT_DATE]s with 1 row showing null values (although my data does include rows)

I bet you are trying to get the following out of the query:
SELECT * from
(select [TABLE_NAME], [COUNT_ROWS], [REPORT_DATE] from account_report
) src
pivot
(sum([COUNT_ROWS]) for [REPORT_DATE] in (' + #cols + ')
) piv
Conversely, if you really want the report name pushed out columnwise then you need to adjust your #cols variable.
SELECT #cols = #cols + QUOTENAME(TABLE_NAME) + ',' FROM (select DISTINCT TOP 2 TABLE_NAME ,REPORT_DATE from account_report order by REPORT_DATE desc) as tmp
select #cols = substring(#cols, 0, len(#cols)) --trim "," at end
set #query =
'SELECT * from
(select [REPORT_DATE], [TABLE_NAME], [COUNT_ROWS] from account_report
) src
pivot
(sum([COUNT_ROWS]) for [TABLE_NAME] in (' + #cols + ')
) piv'
execute(#query)

Related

Pivot dates as rows

I have something like this:
From this query
SELECT DISTINCT Securitization, SUM(RemittableCollections) [RemittableCollections], ReportingDate
FROM Securitization.dbo.SecuritizationReporting
GROUP BY Securitization,ReportingDate
What I want is the Reporting dates to be on the rows, so I will have securitzation as the columns and then for each reporting date I will have a sum of Remittable collections, how can I do this?
This is what I am trying to do but it doesnt work
SELECT DISTINCT Securitization, ReportingDate
FROM Securitization.dbo.SecuritizationReporting
PIVOT
(
SUM(RemittableCollections)
for dates in (SELECT DISTINCT ReportingDate FROM Securitization.dbo.SecuritizationReporting )
)
GROUP BY Securitization,ReportingDate
Untested, but perhaps this will help
Declare #SQL varchar(max) = '
Select *
From (Select Distinct
Securitization
,ReportingDate
,RemittableCollections
From Securitization.dbo.SecuritizationReporting
) src
Pivot ( sum(RemittableCollections) for ReportingDate in ( ' + Stuff((Select Distinct
',' + QuoteName(ReportingDate)
From Securitization.dbo.SecuritizationReporting
Order By 1
For XML Path('')),1,1,'') +' ) ) pvt
'
--Print(#SQL)
Exec(#SQL)
EDIT - Remove NULLS
Declare #NoNulls varchar(max) = Stuff( (
Select Distinct
',' + QuoteName(ReportingDate) +' = IsNull(' + QuoteName(ReportingDate) +',0)'
From Securitization.dbo.SecuritizationReporting
Order By 1
For XML Path('')),1,1,'')
Declare #SQL varchar(max) = '
Select [Securitization]
,' + #NoNulls + '
From (Select Distinct
Securitization
,ReportingDate
,RemittableCollections
From Securitization.dbo.SecuritizationReporting
) src
Pivot ( sum(RemittableCollections) for ReportingDate in ( ' + Stuff((Select Distinct
',' + QuoteName(ReportingDate)
From Securitization.dbo.SecuritizationReporting
Order By 1
For XML Path('')),1,1,'') +' ) ) pvt
'
--Print(#SQL)
Exec(#SQL)

How to make SQL Pivot display more than one row

I was able to display every row in column using pivot however when there are multiple values, it displays only one of the row values. My suspicion lies on the MAX function in the for loop, however, have not been able to find a successful replacement.
I've tried other SQL functions.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
SELECT #cols = STUFF((SELECT ',' + QUOTENAME(Provincia)
FROM Codigos_Postales
GROUP BY Provincia
ORDER BY Provincia
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET #query = N'SELECT Poblacion,' + #cols + N' from
(
select * from Codigos_Postales
) x
pivot
(
MAX(Codigo_Postal)
for Provincia in (' + #cols + N')
) p ORDER BY Poblacion ASC'
EXEC sp_executesql #query;
Table I'm trying to pivot:
Result:
Expected Result:
If I understand corerctly, adding ROW_NUMBER to your source data will do the trick. The sample PIVOT script will be as below. Just ignore the RN column from your final output, that's it.
SET #query =
N'SELECT Poblacion,' + #cols + N' from
(
SELECT
ROW_NUMBER() OVER (ORDER BY Provincia) RN,
*
FROM Codigos_Postales
) x
PIVOT
(
MAX(Codigo_Postal)
FOR Provincia IN (' + #cols + N')
) p ORDER BY Poblacion ASC'

SQL - Pivoting on Column and Row Values

I'm trying to Pivot a Table on X and Y position. The table is in a format similar to below.
Each row has a value which is relative to its Row and Column Position.'AThing' and 'FileName' are to be ignored in the data set.
So if this was pivoted we would get:
Iv'e been trying for a while but can't seem to figure it out, any ideas?
EDIT: Number of Fields are dynamic per 'FileName'. I have managed to extract the column names but not the data using:
-- Construct List of Columns to Pivot
SELECT #PivotCols =
STUFF(
(SELECT ',' + QUOTENAME(FieldName)
FROM #Data
GROUP BY ColPos, FieldName
ORDER BY ColPos ASC
FOR XML PATH(''),TYPE).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #PivotQuery =
SELECT ' + #PivotCols + N'
FROM
(
SELECT ColPos, FieldName
FROM #Data
GROUP BY ColPos, FieldName
) x
PIVOT
(
MIN(ColPos)
FOR FieldName IN (' + #PivotCols + N')
) p'
EXEC sp_executesql #PivotQuery
Please try this code:
DECLARE #columns NVARCHAR(MAX), #sql NVARCHAR(MAX);
SET #columns = N'';
SELECT #columns += N', p.' + QUOTENAME(FieldName)
FROM (SELECT distinct p.FieldName FROM Tablename AS p
) AS x;
SET #sql = N'
SELECT ' + STUFF(#columns, 1, 2, '') + '
FROM
(
SELECT p.Value, p.FieldName, p.RowPos
FROM Tablename AS p
) AS j
PIVOT
(
MAX(Value) FOR FieldName IN ('
+ STUFF(REPLACE(#columns, ', p.[', ',['), 1, 1, '')
+ ')
) AS p;';
PRINT #sql;
EXEC sp_executesql #sql;

SQL Pivot Query

I have the below data in SQL:
Now, I would like to pivot it base on the "CostCenterNumber" field to obtain this:
Try this one:
DECLARE #cols as varchar(max)
DECLARE #sql as varchar(max)
SELECT #cols = coalesce(#cols + ',','') + '[' + CostCenterNumber + ']' FROM #MyTable
SET #sql =
'SELECT Year, GLClass, Code, GLDescription, ' + #cols + '
FROM (
SELECT *
FROM #MyTable
) as P
PIVOT
(
SUM(Total)FOR [CostCenterNumber] IN (' + #cols + ')
)AS pvt'
EXEC(#sql)
I suggest you to use where and between condition from your query

SELECT inside pivot incorrect

SSMS is highlighting that something is wrong on the line FOR urlsByFilm.Media_Type_ID IN...
BEGIN
SELECT urlsByFilm.Film_ID, urlsByFilm.Media_Type_ID, urlsByFilm.Media_File_Name
FROM [dbo].[Film_Media_Item] urlsByFilm
PIVOT
(
MAX(urlsByFilm.Media_File_Name)
FOR urlsByFilm.Media_Type_ID IN (SELECT DISTINCT Media_Type_ID FROM [dbo].[Film_Media_Item])
) AS pivot
WHERE API_ID in (#API_IDs)
END
I cannot run this, can you help?
you can't have SQL expression in the IN clause, you need to specify the values.
MAX(urlsByFilm.Media_File_Name)
FOR urlsByFilm.Media_Type_ID IN
(SELECT DISTINCT Media_Type_ID FROM [dbo].[Film_Media_Item])
You need to use dynamic SQL to achieve what you are doing.
your query would like this, with dynamic SQL
DECLARE #cols NVARCHAR(2000)
SELECT #cols = STUFF(( SELECT DISTINCT
'],[' + Media_Type_ID
[dbo].[Film_Media_Item]
ORDER BY '],[' + Media_Type_ID
FOR XML PATH('')
), 1, 2, '') + ']'
DECLARE #query NVARCHAR(4000)
SET #query = N'SELECT Media_File_Name, '+
#cols +'
FROM
(SELECT urlsByFilm.Film_ID, urlsByFilm.Media_Type_ID, urlsByFilm.Media_File_Name
FROM [dbo].[Film_Media_Item] urlsByFilm)p
PIVOT
(
MAX(urlsByFilm.Media_File_Name)
FOR urlsByFilm.Media_Type_ID IN ( '+
#cols +' )
) AS pvt
WHERE API_ID in (#API_IDs)'
EXECUTE(#query)