I am using dynamic pivot scrip for my report. Below is my script.
DECLARE #Columns VARCHAR(MAX)
set #Columns= ''
SELECT #Columns = #Columns + (QUOTENAME(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20))))) + ',') FROM efoxsfc.dbo.FTX_FA_Calender
WHERE 1=1
AND CAST(dates AS DATETIME) >= DATEADD(mm, -35 ,DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0))
AND dates <= DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)
SET #Columns = LEFT(#Columns, LEN(#Columns) - 1)
DECLARE #SQL NVARCHAR(MAX)
set #SQL= ''
SET #SQL =
'WITH BaseData AS
(
select
vendor_code,
RTRIM(LTRIM(cast(datename(month, [CLOSED_DATE]) as char(15))))+'','' + RTRIM(LTRIM(cast(year([CLOSED_DATE]) as char(20)))) as [CLOSED_DATE],
count(vendor_code) as [No. of Case]
from #teamp t WITH (NOLOCK)
where
[CLOSED_DATE] is not null
group by
vendor_code, CLOSED_DATE
)
SELECT *
FROM BaseData
PIVOT
(
sum([No. of Case])
FOR CLOSED_DATE IN (' + #Columns + ')
) AS PivotTable'
EXECUTE sp_executesql #SQL
where will be my isnull function so that will be replace null with zero.
Please advice !!
This is my new Print #SQL
WITH BaseData AS
(
select
vendor_code,
RTRIM(LTRIM(cast(datename(month, [CLOSED_DATE]) as char(15))))+',' + RTRIM(LTRIM(cast(year([CLOSED_DATE]) as char(20)))) as [CLOSED_DATE],
count(vendor_code) as [No. of Case]
from #teamp t WITH (NOLOCK)
where
[CLOSED_DATE] is not null
group by
vendor_code, CLOSED_DATE
)
SELECT ISNULL([November,2012],0)AS[November,2012],ISNULL([December,2012],0)AS[December,2012],ISNULL([January,2013],0)AS[January,2013],ISNULL([February,2013],0)AS[February,2013],ISNULL([March,2013],0)AS[March,2013],ISNULL([April,2013],0)AS[April,2013],ISNULL([May,2013],0)AS[May,2013],ISNULL([June,2013],0)AS[June,2013],ISNULL([July,2013],0)AS[July,2013],ISNULL([August,2013],0)AS[August,2013],ISNULL([September,2013],0)AS[September,2013],ISNULL([October,2013],0)AS[October,2013],ISNULL([November,2013],0)AS[November,2013],ISNULL([December,2013],0)AS[December,2013],ISNULL([January,2014],0)AS[January,2014],ISNULL([February,2014],0)AS[February,2014],ISNULL([March,2014],0)AS[March,2014],ISNULL([April,2014],0)AS[April,2014],ISNULL([May,2014],0)AS[May,2014],ISNULL([June,2014],0)AS[June,2014],ISNULL([July,2014],0)AS[July,2014],ISNULL([August,2014],0)AS[August,2014],ISNULL([September,2014],0)AS[September,2014],ISNULL([October,2014],0)AS[October,2014],ISNULL([November,2014],0)AS[November,2014],ISNULL([December,2014],0)AS[December,2014],ISNULL([January,2015],0)AS[January,2015],ISNULL([February,2015],0)AS[February,2015],ISNULL([March,2015],0)AS[March,2015],ISNULL([April,2015],0)AS[April,2015],ISNULL([May,2015],0)AS[May,2015],ISNULL([June,2015],0)AS[June,2015],ISNULL([July,2015],0)AS[July,2015],ISNULL([August,2015],0)AS[August,2015],ISNULL([September,2015],0)AS[September,2015],ISNULL([October,2015],0)AS[October,2015]FROM BaseData
PIVOT
(
sum([No. of Case])
FOR CLOSED_DATE IN ([November,2012],[December,2012],[January,2013],[February,2013],[March,2013],[April,2013],[May,2013],[June,2013],[July,2013],[August,2013],[September,2013],[October,2013],[November,2013],[December,2013],[January,2014],[February,2014],[March,2014],[April,2014],[May,2014],[June,2014],[July,2014],[August,2014],[September,2014],[October,2014],[November,2014],[December,2014],[January,2015],[February,2015],[March,2015],[April,2015],[May,2015],[June,2015],[July,2015],[August,2015],[September,2015],[October,2015])
) AS PivotTable
This is my new Print #SQL
You need to declare another variable:
DECLARE #Columns2 VARCHAR(MAX) = ''
Then do the main thing:
SELECT #Columns2 = #Columns2 + 'ISNULL(' + (QUOTENAME(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20))))) + ', 0) AS ' + (QUOTENAME(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20))))) + ',') FROM efoxsfc.dbo.FTX_FA_Calender
WHERE 1=1
AND CAST(dates AS DATETIME) >= DATEADD(mm, -35 ,DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0))
AND dates <= DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)
SET #Columns2 = LEFT(#Columns2, LEN(#Columns2) - 1)
Then use it like:
...
SELECT ' + #Columns2 + '
FROM BaseData
PIVOT
...
Related
so I've been working on a dynamic pivot script and I've almost got it to work, but I'm having issues with declared variables. Here's my code:
DECLARE #start_date DATE
DECLARE #end_date DATE
SET #start_date = CAST(DATEADD(dd,((DATEDIFF(dd,'17530101',GETDATE())/7)*7)-7,'17530101') AS DATE)
SET #end_date = CAST(DATEADD(dd,((DATEDIFF(dd,'17530101',GETDATE())/7)*7)-1,'17530101') AS DATE)
DECLARE #cols AS NVARCHAR(MAX)='';
DECLARE #query AS NVARCHAR(MAX)='';
SELECT #cols = #cols + QUOTENAME(TicketDate) + ','
FROM
(SELECT DISTINCT TOP 14 ad.TicketDate
FROM AttendDet ad
WHERE CAST(ad.TicketDate AS DATE) BETWEEN #start_date AND #end_date
AND ad.EmplCode IS NOT NULL
ORDER BY ad.TicketDate) as dates
SELECT #cols = SUBSTRING(#cols, 0, LEN(#cols))
SET #query =
'SELECT * FROM
(
SELECT
CAST(ad.EmplName AS NVARCHAR(MAX)) AS [EmplName],
CAST(ad.TicketDate AS DATE) AS [TicketDate],
ROUND(ad.TotActTime, 2) AS [TotalHrs]
FROM AttendDet ad
WHERE ad.EmplCode IS NOT NULL
AND ad.AttendCode <> 9999
AND CAST(ad.TicketDate AS DATE) BETWEEN (' + #start_date + ') AND (' + #end_date + ')
) basedata
PIVOT
(
SUM(TotalHrs) FOR TicketDate IN (' + #cols + ')
) piv'
EXECUTE(#query)
The line that is causing an error is this one:
AND CAST(ad.TicketDate AS DATE) BETWEEN (' + #start_date + ') AND (' + #end_date + ')
The error I get is: "The data types varchar and date are incompatible in the add operator." I tried changing the data types to VARCHAR, but that didn't work, when I do that I get this error: Conversion failed when converting date and/or time from character string.
I know I'm in the right direction, because if I hardcode that line manually, for example:
AND CAST(ad.TicketDate AS DATE) BETWEEN ''10/22/18'' AND ''10/28/18''
It works perfectly as expected, but I obviously don't want to do that, as it would defeat the entire purpose of the script. The whole thing should work as long as #start_data and #end_date are set, but I'm stuck on how to finish this. I've been trying all sorts of things for the last hour and can't figure it out
Thanks in advance
You need to cast it to varchar because SQL is interpreting the + as addition versus concatenation here.
DECLARE #start_date DATE = getdate()
DECLARE #end_date DATE = getdate()
DECLARE #cols varchar(10) = ''
DECLARE #query varchar(max)
SET #query =
'SELECT * FROM
(
SELECT
CAST(ad.EmplName AS NVARCHAR(MAX)) AS [EmplName],
CAST(ad.TicketDate AS DATE) AS [TicketDate],
ROUND(ad.TotActTime, 2) AS [TotalHrs]
FROM AttendDet ad
WHERE ad.EmplCode IS NOT NULL
AND ad.AttendCode <> 9999
AND CAST(ad.TicketDate AS DATE) BETWEEN ''' + cast(#start_date as varchar) + ''' AND ''' + cast(#end_date as varchar) + '''
) basedata
PIVOT
(
SUM(TotalHrs) FOR TicketDate IN (' + #cols + ')
) piv'
print #query
So your query would be like so. Notice I changed the command to print instead of execute so you can see what it looks like:
DECLARE #start_date DATE
DECLARE #end_date DATE
SET #start_date = CAST(DATEADD(dd,((DATEDIFF(dd,'17530101',GETDATE())/7)*7)-7,'17530101') AS DATE)
SET #end_date = CAST(DATEADD(dd,((DATEDIFF(dd,'17530101',GETDATE())/7)*7)-1,'17530101') AS DATE)
DECLARE #cols AS NVARCHAR(MAX)='';
DECLARE #query AS NVARCHAR(MAX)='';
SELECT #cols = #cols + QUOTENAME(TicketDate) + ','
FROM
(SELECT DISTINCT TOP 14 ad.TicketDate
FROM AttendDet ad
WHERE CAST(ad.TicketDate AS DATE) BETWEEN #start_date AND #end_date
AND ad.EmplCode IS NOT NULL
ORDER BY ad.TicketDate) as dates
SELECT #cols = SUBSTRING(#cols, 0, LEN(#cols))
SET #query =
'SELECT * FROM
(
SELECT
CAST(ad.EmplName AS NVARCHAR(MAX)) AS [EmplName],
CAST(ad.TicketDate AS DATE) AS [TicketDate],
ROUND(ad.TotActTime, 2) AS [TotalHrs]
FROM AttendDet ad
WHERE ad.EmplCode IS NOT NULL
AND ad.AttendCode <> 9999
AND CAST(ad.TicketDate AS DATE) BETWEEN ''' + cast(#start_date as varchar) + ''' AND ''' + cast(#end_date as varchar) + '''
) basedata
PIVOT
(
SUM(TotalHrs) FOR TicketDate IN (' + #cols + ')
) piv'
--EXECUTE(#query)
print #query
This should work:
AND CAST(ad.TicketDate AS DATE) BETWEEN (' + CONVERT(varchar(11),#start_date,101) + ') AND (' + CONVERT(varchar(11),#end_date,101) + ')
You have a couple of options.
Using the + operator to concatenate strings, all of the values have to be strings themselves, and you can't implicitly convert a DATE to a string, as your error messages says. You can, though, wrap both date variables in explicit CASTs, or CONVERTs if that's your bag:
(' + CAST(#start_date AS VARCHAR(10)) + ') AND (' + CAST(#end_date AS VARCHAR(10)) + ')
If your version supports it (2012+), just use CONCAT. It takes care of the conversions for you.
SET #query = CONCAT(
'SELECT * FROM
(
SELECT
CAST(ad.EmplName AS NVARCHAR(MAX)) AS [EmplName],
CAST(ad.TicketDate AS DATE) AS [TicketDate],
ROUND(ad.TotActTime, 2) AS [TotalHrs]
FROM AttendDet ad
WHERE ad.EmplCode IS NOT NULL
AND ad.AttendCode <> 9999
AND CAST(ad.TicketDate AS DATE) BETWEEN (',
#start_date,
') AND (',
#end_date,
')
) basedata
PIVOT
(
SUM(TotalHrs) FOR TicketDate IN (',
#cols,
')
) piv'
)
I am creating a dynamic pivot query that shows the total NetAmount per Week of every Customers within a given date range. The problem is it doesn't ADD ALL the NetAmount within the Week. Here are the data of tblSampleSalesInvoices:
Here is my script.
CREATE PROCEDURE uspSalesWeeklySummary
(
#CustomerId INT,
#FromDate DATETIME,
#ToDate DATETIME
)
AS
SET NOCOUNT ON
DECLARE #Query AS VARCHAR(MAX)
DECLARE #DateStart DATETIME = #FromDate
DECLARE #tmp TABLE ([Date] VARCHAR(MAX))
DECLARE #Month VARCHAR(MAX)
DECLARE #Day VARCHAR(MAX)
DECLARE #ColumnHeader VARCHAR(MAX)
DECLARE #Headers VARCHAR(MAX)
WHILE DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #DateStart), '19050101') <= DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #ToDate), '19050101')
BEGIN
SET #month = DATENAME(Month, DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #DateStart), '19050101'))
SET #day = CAST( DATEPART(DD, DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #DateStart), '19050101')) AS VARCHAR(MAX) )
SET #ColumnHeader = 'Week ' + CAST(DatePart(WEEK,#DateStart) AS VARCHAR(MAX)) + ' - ' + CAST(Year(DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #DateStart), '19050101')) AS VARCHAR(MAX)) + ' - ' + #month + ' - ' + #day
INSERT INTO #tmp ([Date])
VALUES (#ColumnHeader)
SET #DateStart = DATEADD(DD, 7, #DateStart)
END
SELECT #Headers = ISNULL(#Headers + ',','') + QUOTENAME(t.[Date])
FROM #tmp t
SET #Headers = #Headers + ',[Grand Total]'
SET #Query =
'
DECLARE #CustomerId INT = ' + CAST(#CustomerId AS VARCHAR) + '
DECLARE #FromDate DATETIME = CAST(''' + CAST(#FromDate AS VARCHAR) + ''' AS DATETIME)
DECLARE #ToDate DATETIME = CAST(''' + CAST(#ToDate AS VARCHAR) + ''' AS DATETIME)
DECLARE #Headers VARCHAR(MAX) = ''' + CAST(#Headers AS VARCHAR(MAX)) + '''
SELECT *
FROM
(
SELECT c.CustomerName AS CustomerName,
''Week '' + CAST(DatePart(WEEK,si.TransactionDate) AS VARCHAR(MAX)) + '' - ''
+ CAST(Year(DATEADD(WEEK, DATEDIFF(WEEK, ''19050101'', si.TransactionDate), ''19050101'')) AS VARCHAR(MAX)) + '' - ''
+ CAST(DATENAME(Month, DATEADD(WEEK, DATEDIFF(WEEK, ''19050101'', si.TransactionDate), ''19050101'')) AS VARCHAR(MAX)) + '' - ''
+ CAST(DATEPART(DD, DATEADD(WEEK, DATEDIFF(WEEK, ''19050101'', si.TransactionDate), ''19050101'')) AS VARCHAR(MAX)) AS Header,
SUM(si.NetAmount) AS NetAmount
FROM tblSampleSalesInvoices si
LEFT OUTER JOIN tblSampleCustomers c ON c.Id = si.CustomerId
WHERE (si.TransactionDate BETWEEN #FromDate AND DATEADD(WEEK, DATEDIFF(WEEK, ''19050101'', DATEADD(DD, 7 , #ToDate)), ''19050101''))
AND (si.CustomerId = #CustomerId OR #CustomerId = 0)
GROUP BY c.CustomerName, si.TransactionDate
UNION ALL
SELECT c.CustomerName AS CustomerName,
''Grand Total'' AS Header,
SUM(si.NetAmount) AS NetAmount
FROM tblSampleSalesInvoices si
LEFT OUTER JOIN tblSampleCustomers c ON c.Id = si.CustomerId
WHERE (si.TransactionDate BETWEEN #FromDate AND DATEADD(WEEK, DATEDIFF(WEEK, ''19050101'', DATEADD(DD, 7 , #ToDate)), ''19050101''))
AND (si.CustomerId = #CustomerId OR #CustomerId = 0)
GROUP BY c.CustomerName
) AS BaseData
PIVOT
(
SUM(NetAmount)
FOR Header IN (' + #Headers + ')
) AS Pivoting'
EXEC (#Query)
GO
EXEC uspSalesWeeklySummary 0,'01/01/2016','02/01/2016'
In this script the SUM of NetAmount will be 10000 only because From the Day of Jan 1, 2016 until Feb 1,2016 only 1 transaction (TR0002) has been made. But when I place Dec 27,2015 and Feb 1,2016 in the parameters. It shows only the NetAmount of TR0001 instead of 25000 which the SUM of TR0001 and TR0002.
If you are looking for week numbers relative to a start date and can create # tables then this might suit
CREATE PROCEDURE uspSalesWeeklySummary
(
#CustomerId INT,
#FromDate DATETIME,
#ToDate DATETIME
)
AS
SET NOCOUNT ON
set datefirst 1
/*
create table tblSampleSalesInvoices (id int,transactionNo int,customerid int,TransactionDate date,netamount int)
insert into tblSampleSalesInvoices values
(1,1,1,'2015-12-29',15000),
(2,2,1,'2016-01-01',15000),
(3,3,2,'2016-03-01',15000),
(4,4,3,'2016-04-01',15000),
(5,5,4,'2016-06-01',15000),
(6,6,1,'2016-09-01',15000),
(7,7,2,'2016-10-01',15000),
(8,8,3,'2016-12-01',15000),
(9,9,4,'2017-01-01',15000),
(10,10,1,'2017-04-01',15000),
(11,11,2,'2017-07-01',15000),
(12,12,3,'2017-10-01',15000),
(13,13,4,'2017-12-01',15000)
*/
--declare #CustomerId INT = 1
--declare #FromDate DATETIME = '2015-12-27'
--declare #ToDate DATETIME = '2016-02-01'
DECLARE #Query AS VARCHAR(MAX)
DECLARE #DateStart DATETIME = #FromDate
IF OBJECT_ID(N'tempdb..#Tempdates') IS NOT NULL
BEGIN
DROP TABLE #Tempdates
END
declare #id int = 0
create table #tempdates (id int,[lodate] date, [hidate] date ,yyyy varchar(4), mm varchar(max), dd int,txt varchar(max))
DECLARE #Month VARCHAR(MAX)
DECLARE #Day VARCHAR(MAX)
DECLARE #ColumnHeader VARCHAR(MAX)
DECLARE #Headers VARCHAR(MAX)
WHILE DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #DateStart), '19050101') <= DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #ToDate), '19050101')
BEGIN
set datefirst 1
SET #month = DATENAME(Month, DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #DateStart), '19050101'))
SET #day = CAST( DATEPART(DD, DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #DateStart), '19050101')) AS VARCHAR(MAX) )
SET #ColumnHeader = 'Week ' + CAST(DatePart(WEEK,#DateStart) AS VARCHAR(MAX)) + ' - ' +
CAST(Year(DATEADD(WEEK, DATEDIFF(WEEK, '19050101', #DateStart), '19050101')) AS VARCHAR(MAX)) + ' - ' + #month + ' - ' + #day
set #id = #id + 1
insert into #tempdates (id,[lodate],[hidate],yyyy,mm,dd,txt)
values (#id,#datestart,dateadd(dd,6,#datestart),
year(#datestart),
datename(month,#datestart),day(#datestart),
'Week ' + cast(#id as varchar(2)) + ' - ' + cast(datename(month,#datestart) as varchar(max)) + ' - ' + cast(day(#datestart) as varchar(max))
)
SET #DateStart = DATEADD(DD, 7, #DateStart)
END
update #tempdates
set hidate = #todate where id = #id
SELECT #Headers = ISNULL(#Headers + ',','') + QUOTENAME(t.[txt])
FROM #tempdates t
SET #Headers = #Headers + ',[Grand Total]'
--select #headers headers
--select * from #tempdates
set #query =
'
DECLARE #CustomerId INT = ' + CAST(#CustomerId AS VARCHAR) + '
DECLARE #FromDate DATETIME = CAST(''' + CAST(#FromDate AS VARCHAR) + ''' AS DATETIME)
DECLARE #ToDate DATETIME = CAST(''' + CAST(#ToDate AS VARCHAR) + ''' AS DATETIME)
DECLARE #Headers VARCHAR(MAX) = ''' + CAST(#Headers AS VARCHAR(MAX)) + '''
SELECT *
FROM
(
SELECT si.customerid,
t.txt as header,
SUM(si.NetAmount) AS NetAmount
FROM tblsamplesalesinvoices si
left join #tempdates t on si.Transactiondate between lodate and hidate
--LEFT OUTER JOIN tblSampleCustomers c ON c.Id = si.CustomerId
WHERE si.TransactionDate BETWEEN #FromDate AND DATEADD(WEEK, DATEDIFF(WEEK, ''19050101'', DATEADD(DD, 7 , #ToDate)), ''19050101'')
AND (si.CustomerId = #CustomerId OR #CustomerId = 0)
GROUP BY -- c.CustomerName,
si.customerid
,
t.txt
UNION ALL
SELECT si.CustomerId,
''Grand Total'' AS Header,
SUM(si.NetAmount) AS NetAmount
FROM tblsamplesalesinvoices si
-- LEFT OUTER JOIN tblSampleCustomers c ON c.Id = si.CustomerId
WHERE (si.TransactionDate BETWEEN #FromDate AND DATEADD(WEEK, DATEDIFF(WEEK, ''19050101'', DATEADD(DD, 7 , #ToDate)), ''19050101''))
AND (si.CustomerId = #CustomerId OR #CustomerId = 0)
GROUP BY si.customerid
) s
PIVOT
(
SUM(NetAmount)
FOR Header IN (' + #Headers + ')
) AS Pivoting'
--select #query
exec (#query)
IF OBJECT_ID(N'tempdb..#Tempdates') IS NOT NULL
BEGIN
DROP TABLE #Tempdates
END
go
Please note dates are UK localised
Can you help me how to use DISTINCT in this query?
DECLARE #ReadData NVARCHAR(MAX);
SET #ReadData = 'SELECT ROW_NUMBER() OVER (ORDER BY RM.ReceiverDate) AS [S. No.]
,DISTINCT RM.ReceiverId
,RM.ReceiverDateas [Receiver Date]
,VM.VendorName as [Vendor Name]
,VM.VendorID
FROM Receiver RM
LEFT OUTER JOIN VendorMaster VM on VM.VendorID = RM.VendorId
WHERE ['+ #ColumnName + '] LIKE
CASE WHEN ' + #Filter+ ' = 0 THEN ''%' + #Value + '%'''+
' WHEN ' + #Filter + ' = 1 THEN '''+ #Value + '%'''+
' WHEN ' + #Filter + ' = 2 THEN ''%' + #Value +''' END
AND VM.IsActive = 1
AND RM.VendorID = CASE WHEN ' + CONVERT(VARCHAR, #VendorID) + ' = ''-1'' THEN RM.VendorID
ELSE '+ CONVERT(VARCHAR, #VendorID) +' END
AND (RM.ReceiverDate BETWEEN ' + CHAR(39) + CONVERT(VARCHAR(23), #FromDate, 126) + CHAR(39) +' AND ' + CHAR(39) + CONVERT(VARCHAR(23), #ToDate, 126) + CHAR(39) +')
ORDER BY RM.ReceiverDate '
My question is: how to add DISTINCT to the ReceiverId ?
I get this error:
Incorrect syntax near the keyword 'DISTINCT'.
in the C# code behind
with cte
as
(
Select ROW_NUMBER() OVER (PARTITION BY ReceiverId ORDER BY ReceiverId ) AS dupCount, *
from(
SELECT ROW_NUMBER() OVER (ORDER BY ReceivedDate) AS [S. No.]
,RM.ReceiverId
,RM.ReceiverName'
,VM.VendorName
, XYZ columns .....
From Receiver RM
LEFT OUTER JOIN VendorMaster VM on VM.VendorID = RM.VendorId
) tab
)
select S. No.
,ReceiverId
,ReceiverName
,VendorName
, XYZ columns
from cte
where dupcount=1;
try using cte.
DECLARE #ReadData NVARCHAR(MAX);
set #ReadData = 'SELECT *
,ROW_NUMBER() OVER (ORDER BY ReceivedDate) AS [S. No.]
FROM (SELECT DISTINCT ReceiverId,
ReceivedDate
,ReceiverName
, XYZ columns .....
From Receiver .........
INNER JOIN .......)'
You can't use the row_number and distinct on same level.
I have a stored procedure like this:
ALTER procedure [dbo].[ParkingDeatailsReportnew]
#startdate nvarchar(100),
#enddate nvarchar(100)
as
begin
DECLARE #cols AS NVARCHAR(MAX), #query AS NVARCHAR(MAX)
select #cols =
STUFF((SELECT distinct ',' + QUOTENAME(Vtype) from VType_tbl FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ,1,1,'')
set #query =
'SELECT Date, ' + #cols + '
from ( select v.Vtype, convert(date, dtime) as Date
from Transaction_tbl t inner join VType_tbl v on t.vtid = v.vtid where dtime between ''' + #startdate + ''' and ''' + #enddate +
'''and locid IN ' + (select CAST(l.Locid as varchar(max)) from Location_tbl l)
+ ' ) d pivot ( count(Vtype) for Vtype in (' + #cols + ') ) p '
execute(#query)
end
While executing this am getting error like this:
Subquery returned more than 1 value. This is not permitted when the
subquery follows =, !=, <, <= , >, >= or when the subquery is used as
an expression.
How i can pass more than 1 value in my sub query?
I'd say your problem lays here:
(select CAST(l.Locid as varchar(max)) from Location_tbl l)
You're trying to form a string from an unknown amount of rows returned from that.
You could just make that part of the string.
Try this one -
ALTER PROCEDURE [dbo].[ParkingDeatailsReportnew]
#startdate NVARCHAR(100),
#enddate NVARCHAR(100)
AS BEGIN
DECLARE
#cols AS NVARCHAR(MAX)
, #query AS NVARCHAR(MAX)
SELECT #cols = STUFF((
SELECT DISTINCT ',' + QUOTENAME(Vtype)
FROM dbo.VType_tbl
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET #query =
'SELECT Date, ' + #cols + '
from (
select v.Vtype, convert(date, dtime) as Date
from Transaction_tbl t
join VType_tbl v on t.vtid = v.vtid
where dtime between ''' + #startdate + ''' and ''' + #enddate + '''
and locid IN (SELECT l.Locid FROM dbo.Location_tbl l)
) d pivot ( count(Vtype) for Vtype in (' + #cols + ') ) p '
EXEC sys.sp_executesql #query
END
I use pivot table but when I execute I got this error please help me I am stuck on this thanks in advance sorry if any mistake and please also tell me that how to handle string in string in sql server I use " '' '',''-'' " but not sure it is correct or not please help me as soon as posible here are the query
SELECT #SQL = 'SELECT '
WHile #I <= #Months
BEGIN
SET #YearMonth = REPLACE(LTRIM(SUBSTRING(CONVERT(VARCHAR, DateAdd(Month, #I, #StartDate), 13), 3,9)), ' ', '-')
SET #ColumnText = #YearMonth
SET #SQL = #SQL + 'ISNULL([' + #YearMonth + '], 0.00) as ''' + #ColumnText + ''','
SET #I = #I +1
END
Set #I = 0
SET #SQL = #SQL + 'Product,Supplier,PackPrice,QuantityInPack,Code,SupplierID,Description,RebateAmount
FROM
(
SELECT p.NAME AS product,p.Code AS Code,P.Description as Description,oi.PackPrice,oi.QuantityInPack AS Packsize,S.ID AS SupplierID,s.[Name] AS Supplier,
CASE when oi.RebateType=2 then (oi.PackPrice*oi.RebateAmount)/100 ELSE oi.RebateAmount END AS RebateAmount ,o.Total as TotalSale,
REPLACE(LTRIM(SUBSTRING(CONVERT(VARCHAR, O.CreatedDate, 13), 3,9)), '' '',''-'') as tdate
FROM dbo.SCM_Product p WITH (NOLOCK)
INNER JOIN SCM_OrderItem oi WITH (NOLOCK) ON oi.ProductId = p.ID
LEFT OUTER JOIN dbo.SCM_Supplier s WITH(NoLock) ON oi.SupplierID=s.ID
LEFT OUTER JOIN SCM_Order o WITH (NOLOCK) ON o.Id = oi.ProductId AND O.Status <> 5 -- CANCELLED
AND O.Deleted = 0
WHERE ('''+#SupplierID+''' IS NULL OR s.ID IN (SELECT * FROM GetIDsTableFromIDsList(#SupplierID)))
AND ('''+#ProductID+''' IS NULL OR p.ID IN (SELECT * FROM GetIDsTableFromIDsList(#ProductID)) )
AND (o.CreatedDate >= '''+ dbo.GetDatePart(#StartDate) +''' AND o.CreatedDate <= '''+ dbo.GetDatePart(#Enddate) +''')
GROUP BY REPLACE(LTRIM(SUBSTRING(CONVERT(VARCHAR, o.CreatedDate, 13), 3,9)), '' '',''-''),
s.ID,p.Code,p.NAME,s.NAME,P.Description,oi.packPrice,oi.QuantityInPack,oi.RebateAmount,oi.RebateType,oi.PackPrice,o.Total
) SD
PIVOT
( SUM( SD.TotalSale) FOR SD.tdate IN ('
WHile #I <= #Months
BEGIN
SET #YearMonth = REPLACE(LTRIM(SUBSTRING(CONVERT(VARCHAR, DateAdd(Month, #I, #StartDate), 13), 3,9)), ' ', '-')
IF #I = #Months
BEGIN
SET #SQL = #SQL + ' [' + #YearMonth + ']'
END
ELSE
BEGIN
SET #SQL = #SQL + ' [' + #YearMonth + '],'
END
SET #I = #I +1
END
SET #SQL = #SQL + ')) as pvt
ORDER BY Supplier '
--EXEC(#SQL)
PRINT #SQL
The easiest way of doing it would be to use QUOTENAME() function,because you could easily miss quote in a large query.
Example:
DECLARE #name AS CHAR(10) = 'Revolver'
DECLARE #sql as NVARCHAR(300) = 'SELECT *
FROM Music.Album
WHERE Name ='+ QUOTENAME(#name,'''')
PRINT #sql;
or
DECLARE #name AS CHAR(10) = 'Revolver'
DECLARE #sql as NVARCHAR(300) = 'SELECT *
FROM Music.Album
WHERE Name ='''+ #name + ''''
PRINT #sql;