Anyone tell me whats wrong with my SQL, having a hard time with this today. The error is:
Msg 156, Level 15, State 1, Line 11
Incorrect syntax near the keyword 'select'.
Msg 102, Level 15, State 1, Line 11
Incorrect syntax near ')'.
SELECT *
FROM (
SELECT
left(datename(month,TransactionDateTime),3) as [month], year(TransactionDateTime) as [year],
count(*) as Total
FROM quotations
) as s
PIVOT
(
SUM(Total)
FOR [year] IN (select distinct year(TransactionDateTime) from quotations)
) AS pivot
The shape I am after is... So years as column names then 12 rows for each month. Below is just to illustrate the shape
// var data = google.visualization.arrayToDataTable([
// ['Month', '2013', '2014', '2015'],
// ['Jan', 10, 30, 31],
// ['Feb', 11, 30, 32],
//]);
The syntax for pivot is as follows (From TechNet):
PIVOT
(
<aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
IN ( [first pivoted column], [second pivoted column], ... [last pivoted column])
) AS <alias for the pivot table>
You can see that inside IN clause there should be column names enclosed in [] which can be a problem if the column names are dynamic. This problem can be easily solved by using dynamic SQL.
Here is an example:
DECLARE #cols AS NVARCHAR(MAX)
DECLARE #query AS NVARCHAR(MAX)
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(year(TransactionDateTime))
FROM Quotations
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #query =
'SELECT *
FROM (
SELECT
left(datename(month,TransactionDateTime),3) as [month], year(TransactionDateTime) as [year],
count(*) as Total
FROM quotations
) as s
PIVOT
(
SUM(Total)
FOR [year] IN (' + #cols + ')
) AS pivot'
EXECUTE(#query)
I don't know what your schema is so there may be a mistake with table/column names. If this doesn't help I can be more precise if you share your schema and a sample data.
The problem is with the following part of your query
(select distinct year(TransactionDateTime) from quotations)
You need to provide a static list of years inside the in clause.
Related
I'm trying to create a dynamic pivot table in SQL that will report based on month and year. I did a bunch of research and was able to come up with the below query:
declare #dynamic nvarchar(max),
#column nvarchar(max);
set #column = N'';
select #column += N'' + datename(month,incurdate) +' '+ datename(year,incurdate) + ','
from (select distinct a.incurdate from artable a) as Transpose
select #column = substring(#column,0,len(#column))
set #dynamic = 'select * from
(
select month, incurdate, dolamount
from artable join dolentry on month = period
) b
pivot(sum(dolamount) for incurdate in (' + #column + ')) as PivotTable'
execute sp_executesql #dynamic
I am able to print the #column variable successfully, but the problems happen when I try to set it in the #dynamic variable. The error message is 'Msg 102, Level 15, State 1, Line 6
Incorrect syntax near '1990'.' 1990 is the first year of the first pivoted column. Any help or tips are appreciated. Thanks!
You need to use QUOTENAME in the following code:
select #column += N'' + QUOTENAME(datename(month,incurdate) +' '+ datename(year,incurdate)) + ','
from (select distinct a.incurdate from artable a) as Transpose
in order to get output like this:
[col01], [col02], [col03], ... , [col04]
As you can see from the docs, the PIVOT syntax requires the pivoting columns to be wrapped in square brackets:
SELECT <non-pivoted column>,
[first pivoted column] AS <column name>,
[second pivoted column] AS <column name>,
...
[last pivoted column] AS <column name>
FROM
(<SELECT query that produces the data>)
AS <alias for the source query>
PIVOT
(
<aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
IN ( [first pivoted column], [second pivoted column],
... [last pivoted column])
) AS <alias for the pivot table>
<optional ORDER BY clause>;
I am trying to use multiple pivot in a single query on same column.
Since i am using same column "month" for all the pivot's, i have added column header to the select list and have added different alias name. Month column has int datatype value. Below is the code:
Select * FROM
(
SELECT
[team],
Count_O,
Count_Of_OA,
Avg,
[month]+ '_a' as month_a,
[month] + '_b' as month_b,
[users]
FROM [#Temp]
) AS X
PIVOT
(
MAX(Count_OA)
FOR [month_a] IN ([4_a], [5_a], [6_b])
) AS PivotTable1
PIVOT
(
MAX(Count_O)
FOR [month_b] IN ([4_b], [5_b], [6_b])
) AS PivotTable2
When i execute this, I get the below error:
Msg 8114, Level 16, State 1, Line 44
Error converting data type nvarchar to int.
Any inputs would be much appreciated.
Try this
Select * FROM
(
SELECT
[team],
Count_O,
Count_Of_OA,
Avg,
Convert(varchar(max),[month])+ '_a' as month_a,
Convert(varchar(max),[month]) + '_b' as month_b,
[users]
FROM [#Temp]
) AS X
PIVOT
(
MAX(Count_OA)
FOR [month_a] IN ([4_a], [5_a], [6_b])
) AS PivotTable1
PIVOT
(
MAX(Count_O)
FOR [month_b] IN ([4_b], [5_b], [6_b])
) AS PivotTable2
I want to use a query to return columns transformed from row from table FloatNAR800 with pivot I have this code but doesn't work for me. Any idea ?
declare #nume_coloane as nvarchar(max),
#dynamic_pivot_query as nvarchar(max)
set #nume_coloane = STUFF ((select ',' + QUOTENAME(TagIndex)
from (select distinct TagIndex from FloatN2_NAR800) sub
order by TagIndex
for xml path(''), type ).value('.', 'nvarchar(max)')
set #dynamic_pivot_query = 'select DateAndTime,' + #nume_coloane +
'from
(select DateAndTime, TagIndex, Val
from FloatN2_NAR800) x
pivot'
When I want to create this query an error appears :
Incorrect syntax near the keyword 'SET'
but I don't know what I do wrong ...
You are missing code... The pivot statement dos not end with the Pivot key word.
You code then...
PIVOT
(
<aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
IN ( [first pivoted column], [second pivoted column],
... [last pivoted column])
) AS <alias for the pivot table>
Take a look here: https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
I would advise you to get the Pivot working first, then make it into a dynamic sql.
I have following query:
select * from dbPratiche
pivot
(
count(Compagnia)
for
(convert(char(3), [Data creazione pratica], 0))
in ([jan],[feb],[mar],[apr],[may],[jun],[jul],[aug],[sep],[October],[nov],[dec])
) pvt
I want to pivot my table on monthname from one [Data creazione pratica] column having date values in it.
But I'm getting an error:
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near '('.
I checked all brackets, all brackets are correct.
Please tell me where I am making a mistake in this query
I solved it through:
select * from (
select convert(char(3), [Data creazione pratica], 0) as monthOF ,[Compagnia]
from dbPratiche where ISNULL([Data creazione pratica],'')!='')as temp
pivot
(
count(Compagnia)
for monthOF in
(jan,feb,mar,apr,may,jun,jul,aug,sep,Oct,nov,dec)
) pvt
I have stuck in a select statement, converting rows into columns. I have tried with PIVOT, i was able to convert the single column. But my requirement is little different. I have explained the requirement below.
I have a table structure as below,
I want to select the data as below,
The values in the table are dynamic, which is not a problem for me to deal with that. But i need a way to get the below result.
Could someone please give me a hint on doing it, may be a way to modify the PIVOT below.
select *
from
(
select TSID,AID,Count,BID
from tbl TS
WHERE TS.TPID = 1
) src
pivot
(
sum(Count)
for AID in (AID1,AID2,AID3)
) piv
Thank you..
You may check this fiddle
EDIT
This will work for not previously known column names
DECLARE #Columns AS VARCHAR(MAX)
DECLARE #SQL AS VARCHAR(MAX)
SELECT #Columns = STUFF(( SELECT DISTINCT ',' + AID
FROM Table1
FOR
XML PATH('')
), 1, 1, '')
SET #SQL = '
;WITH MyCTE AS
(
SELECT TSID,
AID,
STUFF(( SELECT '','' + CONVERT(VARCHAR,[Count] )
FROM Table1 I Where I.TSID = O.TSID
FOR
XML PATH('''')
), 1, 1, '''') AS CountList
FROM Table1 O
GROUP BY TSID,
AID
)
SELECT *
FROM MyCTE
PIVOT
(
MAX(CountList)
FOR AID IN
(
' + #Columns + '
)
) AS PivotTable'
EXEC(#SQL)