SQL Server Row Into Column - sql-server

We have a table showing amounts (CHGCNT) for 3 dates (5-9-2016, 5-10-2016, 5-11-2016) for each store & Depts.
I want to be able to see the records in a table like this:
I already applied the following query
declare #dt as datetime
declare #dt1 as varchar(10)
declare #dt2 as varchar(10)
declare #dt3 as varchar(10)
select distinct #dt = min(effdt) from [HQExtract].[dbo].[FSM_PRICE_TAGCOUNT]
-- print CONVERT(CHAR(10), #dt, 110) + ' ---- ' + CONVERT(CHAR(10), #dt+1 , 110)
set #dt1 = CONVERT(CHAR(10), #dt, 110)
set #dt2 = CONVERT(CHAR(10), #dt +1 , 110)
set #dt3 = CONVERT(CHAR(10), #dt + 2 , 110)
--print #dt1 + ' ---- ' + #dt2 + '-----' + #dt3
SELECT DEPTNM, DEPT, [#dt1] , [#dt2] , [#dt3]
FROM [HQExtract].[dbo].[FSM_PRICE_TAGCOUNT]
PIVOT
(
SUM(CHGCNT)
FOR effdt IN ( [#dt1] , [#dt2] , [#dt3])
) AS P
but it is returning dates

I like the SUM-CASE approach:
SELECT deptnm,
SUM(CASE WHEN effdt = '2016-05-09' THEN chgcnt ELSE 0 END) "2016-05-09",
SUM(CASE WHEN effdt = '2016-05-10' THEN chgcnt ELSE 0 END) "2016-05-10",
SUM(CASE WHEN effdt = '2016-05-11' THEN chgcnt ELSE 0 END) "2016-05-11",
SUM(effdt) Total
FROM [HQExtract].[dbo].[FSM_PRICE_TAGCOUNT]
GROUP BY deptnm;

Related

How to get this using PIVOT?

I have a table something like this:-
DATE AREA
01-01-2018 AREA-1
02-01-2018 AREA-1
03-01-2018 AREA-2
My Desired Result should be something like this:-
AREA 01-01-2018 02-01-2018 03-01-2018
AREA-1 YES YES NO
AREA-2 NO NO YES
How can I get this?
Here is one way using Pivot
SELECT AREA,
COALESCE([01-01-2018], 'NO'),
COALESCE([02-01-2018], 'NO'),
COALESCE([03-01-2018], 'NO')
FROM (SELECT *,
'YES' AS t
FROM Yourtable)a
PIVOT(Max(t)
FOR DATE IN ([01-01-2018],[02-01-2018],[03-01-2018]) ) pv
Even easier method
SELECT AREA,
Max(CASE WHEN date = '01-01-2018' THEN 'YES' ELSE 'NO' END),
Max(CASE WHEN date = '02-01-2018' THEN 'YES' ELSE 'NO' END),
Max(CASE WHEN date = '03-01-2018' THEN 'YES' ELSE 'NO' END)
FROM Yourtable
GROUP BY AREA
Dynamic version
DECLARE #col_list VARCHAR(max)='',
#select_list VARCHAR(max)='',
#sql VARCHAR(max)
SET #col_list = Stuff((SELECT DISTINCT ',' + Quotename(DATE)
FROM Yourtable
FOR xml path('')), 1, 1, '')
SET #select_list = Stuff((SELECT DISTINCT ',COALESCE(' + Quotename(DATE) + ',''NO'') as ' + Quotename(DATE)
FROM Yourtable
FOR xml path('')), 1, 1, '')
SET #sql = '
SELECT AREA,' + #select_list + '
FROM (SELECT *,
''YES'' AS t
FROM Yourtable)a
PIVOT(Max(t)
FOR DATE IN (' + #col_list + ') ) pv'
EXEC (#sql)
Note : Always store dates in Date type instead of varchar

SQL Server Dynamic Pivot Query

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

SQL Server stored procedure SELECT statement with few IF statement

i have constructed my sql statemnet like the below way but i am getting error when try to compile. i know we can build it dynamically in string but like to know can we write statement like this way. please looking for suggestion.
INSERT INTO #tmpHierarchy (
JID ,
EntryDate ,
RefundDate ,
ActionBy ,
Comments ,
CID,
nLevel
)
SELECT
JID, EntryDate, RefundDate, ActionBy, Comments, CID, nLevel
FROM
Hierarchy
WHERE 1=1
AND
IF #FromDate <> '' AND #ToDate <> ''
BEGIN
Convert(varchar,EntryDate,112)>= #FromDate AND Convert(varchar,EntryDate,112) <= #ToDate
END
IF #ActionBy <> ''
BEGIN
ActionBy=#ActionBy
END
IF #JID > 0
BEGIN
JID=#JID
END
You actually have to build up a varchar with the query and then execute it:
declare #sql varchar(max)
set #sql = 'INSERT INTO #tmpHierarchy (
JID ,
EntryDate ,
RefundDate ,
ActionBy ,
Comments ,
CID,
nLevel
)
SELECT JID,EntryDate,RefundDate,ActionBy,Comments,CID,nLevel FROM Hierarchy WHERE 1=1'
IF #FromDate <> '' AND #ToDate <> ''
BEGIN
#sql = #sql + ' and Convert(varchar,EntryDate,112)>= #FromDate AND Convert(varchar,EntryDate,112) <= #ToDate'
END
IF #ActionBy <> ''
BEGIN
#sql = #sql + ' and ActionBy=#ActionBy'
END
IF #JID > 0
BEGIN
#sql = #sql + ' and JID=#JID'
END
exec (#sql)
You can do something like this where you combine the IF statements into the WHERE clause
SELECT JID, EntryDate, RefundDate, ActionBy, Comments, CID, nLevel
FROM Hierarchy
WHERE 1 = 1
AND (#FromDate = '' OR #ToDate = '' OR (Convert(varchar, EntryDate, 112) >= #FromDate AND Convert(varchar, EntryDate, 112) <= #ToDate))
AND (#ActionBy = '' OR ActionBy = #ActionBy)
AND (#JID <= 0 OR JID = #JID)

how to include the parameter name as the name of a column in sql

I have a stored procedure that looks something like this :
CREATE PROCEDURE [dbo].[spRS_Get]
#Year Varchar(20),
#Month Varchar(20)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Paramdate datetime;
DECLARE #ParamYear varchar(4);
DECLARE #ParamMonth varchar(2);
DECLARE #Concatt varchar(10);
SET #ParamYear = #Year;
SET #ParamMonth = #Month;
SET #Concatt = #ParamMonth + '-' + '01' + '-' + #ParamYear;
SET #Paramdate = CONVERT(datetime, #Concatt);
SELECT Item
,SUM(CASE WHEN [MONTH] = month(#ParamDate) THEN Sales END) AS month(#ParamDate)
,SUM(CASE WHEN [MONTH] = month(#ParamDate) - 1 THEN Sales END) AS month(#ParamDate) - 1,
,SUM(CASE WHEN [MONTH] = month(#ParamDate) THEN Sales END) - SUM(CASE WHEN [MONTH] = month(#ParamDate) - 1 THEN Sales END) AS month(#ParamDate) - month(#ParamDate) - 1
FROM ABC
GROUP BY Item
In the above query , the part after the AS causes the error.
I want to use the parameter name as the name of the column , but it gives me an error. Is there a way I can use
the parameter name as the name of the month ?
You can only do that by building the select statement as a string and then executing it using the sp_executesql command.
So you'd get something like this:
declare #month0 varchar(2) = cast(month(#paramdate) as varchar(2));
declare #month1 varchar(2) = cast((month(#ParamDate) - 1) as varchar(2));
declare #month2 varchar(2) =
cast((month(#ParamDate) - month(#ParamDate) - 1) as varchar(2));
declare s nvarchar(1024) =
'SELECT Item
, SUM(CASE WHEN [MONTH] = month(#d) THEN Sales END)
AS ''' + #month0 +
''' , SUM(CASE WHEN [MONTH] = month(#d) - 1 THEN Sales END)
AS ''' + #month1 +
''' , SUM(CASE WHEN [MONTH] = month(#d) THEN Sales END) -
SUM(CASE WHEN [MONTH] = month(#d) - 1 THEN Sales END)
AS ''' + #month2 +
''' FROM ABC GROUP BY Item';
EXEC sp_executesql #s, N'#d DATETIME', #ParamDate;

Help with SQL to get Hits per day for today and 1 month prior

I have this SQL now:
CREATE PROCEDURE dbo.sel_Track_HitsLast30Days(
#projectID int
)
AS
BEGIN
DECLARE #FirstDay smalldatetime, #NumberOfMonths int, #priorMonth smalldatetime
set #priorMonth = (SELECT CAST(
(
STR( YEAR( dateadd(m,-1, getDate()) ) ) + '/' +
STR( MONTH( dateadd(m,-1, getDate()) ) ) + '/' +
STR( DAY( dateadd(m,-1, getDate()) ) )
)
AS DateTime
))
Select #FirstDay = #priorMonth, #NumberOfMonths = 1
;WITH Days AS (
SELECT #FirstDay as CalendarDay
UNION ALL
SELECT DATEADD(d, 1, CalendarDay) as CalendarDay
FROM Days
WHERE DATEADD(d, 1, CalendarDay) < DATEADD(m, #NumberOfMonths, #FirstDay+1)
)
SELECT calendarday,foundDate.TotalbyDate,foundDate.date FROM Days
LEFT OUTER JOIN (
SELECT
COUNT(LEFT(visitDateTime, 11)) AS TotalbyDate,substring(convert( char(10), CONVERT( char(10), visitDateTime, 121 ) ), 1, 11) AS date
FROM
dbo.TrackingData
WHERE
visitDateTime >= dateadd(d, datediff(d, 0, getdate()), -30) and projectID = #projectID
GROUP BY substring(convert( char(10), CONVERT( char(10), visitDateTime, 121 ) ), 1, 11)
) foundDate on foundDate.date = CalendarDay
order by
CalendarDay Desc
END
This works ok, but It is not taking into account months with 31 days and I am not getting back today's date for some reason.
Try this (using AdventureWorks as sample database)
DECLARE #today datetime, #NumberOfMonths int, #FirstDay smalldatetime
SELECT #today = '2004-03-09', -- getdate(), tests only
#NumberOfMonths = 1,
#FirstDay = CAST(FLOOR(CAST(
DATEADD(M, -1, #today) AS float)) AS datetime);
WITH Days AS
(
SELECT #FirstDay AS CalendarDay UNION ALL
SELECT DATEADD(d, 1, CalendarDay) AS CalendarDay FROM Days
WHERE DATEADD(d, 1, CalendarDay) < DATEADD(m, #NumberOfMonths, #FirstDay+1)
)
SELECT CONVERT(varchar(10), CalendarDay, 111) as [Date],
COUNT(TransactionDate) as [Count]
FROM Days LEFT JOIN Production.TransactionHistory
ON TransactionDate = Days.CalendarDay
GROUP BY CalendarDay
ORDER BY CalendarDay
Will output
Date Count
---------- -----------
2004/02/09 272
2004/02/10 308
2004/02/11 264
2004/02/12 265
2004/02/13 250
...
EDIT: Updated to include all interval dates
HEre is a modified version of Ruben's answer:
DECLARE #today DATETIME,
#firstDayLastMonth DATETIME,
#daysCount int
SET #today = getDate()
SET #firstDayLastMonth = Dateadd(m,-1,Dateadd(d,-Day(#today) + 1,#today))
Set #daysCount = (select datepart(dd,dateadd(dd,-1,dateadd(mm,1,cast(cast(year(#firstDayLastMonth) as varchar)+'-'+cast(month(#firstDayLastMonth) as varchar)+'-01' as datetime)))))
SELECT substring(convert( char(10), CONVERT( char(10), visitDateTime, 121 ) ), 1, 11) AS [Date], Count(* ) AS [Count]
FROM dbo.TrackingData
WHERE visitdatetime >= Dateadd(d,-#daysCount,#today)
GROUP BY substring(convert( char(10), CONVERT( char(10), visitDateTime, 121 ) ), 1, 11)
ORDER BY substring(convert( char(10), CONVERT( char(10), visitDateTime, 121 ) ), 1, 11)
OK, I got it. Rubens gave me an idea so I modified my SQL like so:
DECLARE #FirstDay SMALLDATETIME,
#NumberOfMonths INT,
#priorMonth SMALLDATETIME,
#firstDayLastMonth DateTime,
#daysCount int
set #firstDayLastMonth = dateadd(m, -1, dateadd(d, -day(getDate()) + 1, getDate()))
set #daysCount = (select datepart(dd,dateadd(dd,-1,dateadd(mm,1,cast(cast(year(#firstDayLastMonth) as varchar)+'-'+cast(month(#firstDayLastMonth) as varchar)+'-01' as datetime)))))
SET #priorMonth = (SELECT Cast((Str(Year(Dateadd(m,-1,Getdate()))) + '/' + Str(Month(Dateadd(m,-1,Getdate()))) + '/' + Str(Day(Dateadd(m,-1,Getdate())))) AS DATETIME))
Declare #before dateTime
Set #before = Dateadd(d,-#daysCount,getdate())
SELECT #FirstDay = #before,
#NumberOfMonths = 1;
WITH days
AS (SELECT #FirstDay AS calendarday
UNION ALL
SELECT Dateadd(d,1,calendarday) AS calendarday
FROM days
WHERE Dateadd(d,1,calendarday) <= Dateadd(m,#NumberOfMonths,#FirstDay))
SELECT Substring(Convert(CHAR(10),Convert(CHAR(10),calendarday,101)),
1,11) ,
founddate.totalbydate,
founddate.DATE
FROM days
LEFT OUTER JOIN (SELECT Count(Left(visitdatetime,11)) AS totalbydate,
Substring(Convert(CHAR(10),Convert(CHAR(10),visitdatetime,101)),
1,11) AS DATE
FROM dbo.trackingdata
WHERE visitdatetime >= Dateadd(d,Datediff(d,0,Getdate()),-29)
AND projectid = 131
GROUP BY Substring(Convert(CHAR(10),Convert(CHAR(10),visitdatetime,101)),
1,11)) founddate
ON founddate.DATE = Substring(Convert(CHAR(10),Convert(CHAR(10),calendarday,101)),
1,11)

Resources