SQL Server 2012 pivot error - sql-server

I'm doing a dynamic pivot to create a cross tab with dates. The #Query generated is :-
SELECT [R_Ref]
,CONCAT(datepart(yyyy,[Transaction_Date]), '-', RIGHT('00' + CONVERT(NVARCHAR(2), datepart(M,[Transaction_Date])), 2)) as 'Month'
,[Transaction_Value]
FROM [T-Files].[dbo].[T_Transactions]
as MyTX
PIVOT (
SUM(MyTX.[Transaction_Value])
FOR MyTX.[Month] IN ( [2016-05], [2016-06], [2016-07])
) p
but this generates these errors
Msg 207, Level 16, State 1, Line 9
Invalid column name 'Month'.
Msg 207, Level 16, State 1, Line 3
Invalid column name 'Transaction_Value'.
I can run the top select without the pivot fine, what's wrong in the PIVOT statement?
TIA :o)

You need to put pivot source in sub-select since you are making some manipulation to generate Month.
SELECT *
FROM (SELECT [R_Ref],
Concat(Datepart(yyyy, [Transaction_Date]), '-', RIGHT('00'+ CONVERT(NVARCHAR(2), Datepart(M, [Transaction_Date])), 2)) AS 'Month',
MyTX.[Transaction_Value]
FROM [T-Files].[dbo].[T_Transactions] AS MyTX) A
PIVOT ( Sum([Transaction_Value])
FOR [Month] IN ( [2016-05],
[2016-06],
[2016-07]) ) p

Related

How to delete 1000 rows at a time with SQL Server OPENQUERY

I need to delete rows in a link server's table, 1000 rows at a time.
My code is the following:
WHILE (SELECT COUNT(*) FROM OPENQUERY (SqlServerAcc, 'SELECT * FROM titles ') > 1000)
BEGIN
DELETE OPENQUERY (SqlServerAcc,
'SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY Id) AS RowNumber FROM tbl) t WHERE RowNumber <= 1000');
END
But I do have errors:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '>'.
at the expression > 1000.
I don't understand why this does not work.
Bonus: how can we make the name of the server not hard-coded; in PRD, it should be SqlServerPrd, but it seems that OPENQUERY does not accept variables for its arguments...

How use money format in pivot in SQL Server

I am using this code. It returns the sum() of price and shows it with delimiter like money format
SELECT
REPLACE(CONVERT(VARCHAR(20), CAST( sum(unitprice) AS MONEY), 1), '.00', '')
FROM
tchargecard_factor
GROUP BY
datetimeentry
and it works fine.
Please tell me how can I get this result from pivot table?
My code is :
'SELECT *, (' + #GrandTotalCol + ') AS [Grand Total]
INTO #temp_MatchesTotal
FROM
(SELECT
idpoint, [last mendub name], pointsalename,
agentname, mobile, remain, typegroupname
FROM
zomorod_webapp_temp.dbo.chargecard_sum_typegroup4) A
PIVOT
(SUM(remain)
FOR typegroupname IN (' +#columnHeaders + ')) B
ORDER BY
idpoint
When I use this code, it is not allowing me to use cast or convert type in sum(remain). I get this error:
Msg 195, Level 15, State 1, Line 9
'REPLACE' is not a recognized aggregate function
How can I fix it?

Incorrect syntax near the keyword 'SELECT' using IN clause

I am having trouble with my query, i am trying to do a pivot table using data from SQL and I want to sum up figures from a table for all years past from 2000.
This is my query
SELECT
*
FROM
(SELECT
Vendor_code, Vendor_name, Ord_date, SubTot,
DateRecieved, CurrencyCode, YearReceived
FROM
[BL_CUSTOM PO HISTORY SUMMARY]) AS S
PIVOT
(SUM(S.SubTot)
FOR s.YearRecived IN (SELECT STUFF((SELECT ', ' + cast(year as VARCHAR(10)) FROM [BL_CUSTOM YEAR COUNT] FOR XML PATH('')),1,1,'')) ) as pvt
I am getting the following error:
Msg 156, Level 15, State 1, Line 33
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 33
Incorrect syntax near ')'.
Refer to the syntax in https://learn.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-2017
I believe your query,
SELECT STUFF((SELECT ', ' + cast(year as VARCHAR(10)) FROM [BL_CUSTOM YEAR COUNT] FOR XML PATH('')),1,1,''))
is causing the problem.

SQL server can not accept median function

I wrote this Median function but it is executing with errors.. Can someone guide me what's wrong in the code?
BEGIN
CREATE TABLE #ITEMORDERDETAILS
(
ITEM CHAR(15),
QTYSHP DECIMAL(21, 6),
RQDATE DATETIME
)
DECLARE #Median FLOAT
DECLARE #ITEM CHAR(15)
DECLARE #ORDERCNT INT
SET #ITEM=#ITEMN
INSERT #ITEMORDERDETAILS
SELECT ITEM,
QTYSHP,
RQDATE
FROM tbl123456
WHERE PRICE != '0'
AND SALESMN != 'WB'
AND RQDATE > ( getdate () - 180 )
AND ITEM = #ITEM
UNION
SELECT ITEM,
QTYSHP,
RQDATE
FROM tbl123
WHERE PRICE != '0'
AND SALESMN != 'WB'
AND RQDATE > ( getdate () - 180 )
AND ITEM = #ITEM
SELECT #ORDERCNT = count (1)
FROM #ITEMORDERDETAILS
--SELECT #ORDERCNT
SELECT #Median = ( sum(QTYSHP) / #ORDERCNT )
FROM #ITEMORDERDETAILS
SELECT #Median AS 'Median'
--SELECT * from #ITEMORDERDETAILS
DROP TABLE #ITEMORDERDETAILS
RETURN #Median
END
ERRORS
Msg 2772, Level 16, State 1, Procedure
f_Get_Average_Order_Size_Median, Line 34 Cannot access temporary
tables from within a function.
Msg 2772, Level 16, State 1, Procedure
f_Get_Average_Order_Size_Median, Line 35 Cannot access temporary
tables from within a function.
Msg 2772, Level 16, State 1, Procedure
f_Get_Average_Order_Size_Median, Line 42 Cannot access temporary
tables from within a function.
Msg 156, Level 15, State 1, Procedure
f_Get_Average_Order_Size_Median, Line 46 Incorrect syntax near the
keyword 'SELECT'.
The reason is in your error message:
Line 34 Cannot access temporary tables from within a function
If you make a function, there are limits to what you can access.
However, if you use SQL Server 2012, you do not need to write your own median function but you can use PERCENTILE_DISC
PERCENTILE_DISC (0.5) WITHIN GROUP (ORDER BY XXXX)
OVER (PARTITION BY YYYY) AS Median

SQL Server append query

I have the following (not working) query:
insert into [MyDB].[dbo].[Reports_StepsStat]
(ActivityID,TaskID,StepIndex,StepStatus,TimeSpanInSeconds,Score)
VALUES (
SELECT
tasks.ActivityID as ActivityID,
tasks.ID as TaskID,
[StepIndex]=item.value('(StepIndex)[1]', 'NVARCHAR(MAX)'),
[StepStatus]=item.value('(Status)[1]', 'NVARCHAR(MAX)'),
[TimeSpanInSeconds] = DATEDIFF(MINUTE, item.value('(StartedOn)[1]', 'datetime'),item.value('(FinishedOn)[1]', 'datetime')),
tasks.Score as Score
FROM
[MyDB].[dbo].[Tasks] as tasks
CROSS APPLY
[Progress].nodes ('//Progress/Steps/ProgressStep') Progress(item)
)
The inner select query (SELECT task.ActivityID..) works perfectly and produces the expected table.
The outer insert into part is supposed to append the result of the inner part to a table by the name of Reports_StepsStat. This does not work.
I have tried and succeeded doing that with SELECT INTO, but apparently SELECT INTO can only be used to create a new table, and not to append to an existing table, which is what I need.
The errors I get are:
Msg 156, Level 15, State 1, Line 6
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near ')'.
I think VALUES ( is not required in your query.
insert into [MyDB].[dbo].[Reports_StepsStat]
(ActivityID,TaskID,StepIndex,StepStatus,TimeSpanInSeconds,Score)
SELECT
tasks.ActivityID as ActivityID,
tasks.ID as TaskID,
[StepIndex]=item.value('(StepIndex)[1]', 'NVARCHAR(MAX)'),
[StepStatus]=item.value('(Status)[1]', 'NVARCHAR(MAX)'),
[TimeSpanInSeconds]=DATEDIFF(MINUTE,item.value('(StartedOn)[1]', 'datetime'),
item.value('(FinishedOn)[1]', 'datetime')),
tasks.Score as Score
FROM [MyDB].[dbo].[Tasks] as tasks
CROSS APPLY [Progress].nodes ('//Progress/Steps/ProgressStep') Progress(item)
Syntax is
insert into a select * from b
so just omit the values (...) surroundng the select...

Resources