I've got a stored procedure with a pivot where data fields become columns. Data that is presently returned has some redundancies and would like to see if there is a way to correct this. The stored procedure is actually feeding a .rdlc report and current output looks like this:
Period | No Of Interim | Excellent | Very Good | Good | Satisfactory | Unsatisfactory
-------------------------------------------------------------------------------------
1 1
12 1
18 1
18 1
18 1
19 1
19 1
2 1
2 1
This is what it needs to look like:
Period | No Of Interim | Excellent | Very Good | Good | Satisfactory | Unsatisfactory
-------------------------------------------------------------------------------------
1 1
2 1 1
12 1
18 1 1 1
19 1 1
Period column needs to sorted in ascending fashion and repeating instances need to be added to the same line.
The stored procedure and corresponding view responsible for output is as follows:
BEGIN
DECLARE #cols NVARCHAR(MAX)
DECLARE #query NVARCHAR(MAX)
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
SELECT #cols = STUFF((SELECT '],[' + [Description]
FROM vQualScoringGrade
GROUP BY [Description]
ORDER BY MAX([orderby]), [Description]
FOR XML PATH('')), 1,2,'') + ']'
SET #query = N'SELECT Period, ' + #cols + ' FROM
(SELECT Period, Description, Value, OrderBy FROM
vQualScoringGrade) p
PIVOT (SUM([Value]) for [Description] IN ( ' + #cols + ' )) AS pvt ORDER BY Period'
execute(#query)
end
SELECT TOP (100) PERCENT Period, Description, GradeCount AS Value, OrderBy
FROM (SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'NoOfInterim' AS Description, COUNT(Number) AS
GradeCount, 1 AS OrderBy
FROM vQualScoringExcellent AS vQualScoringExcellent
GROUP BY Number, Description
UNION
SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'Excellent' AS Description, COUNT(Description) AS
GradeCount, 2 AS OrderBy
FROM vQualScoringExcellent AS vQualScoringExcellent_1
GROUP BY Number, Description
UNION
SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'VeryGood' AS Description, COUNT(Description) AS
GradeCount, 3 AS OrderBy
FROM vQualScoringVeryGood AS vQualScoringVeryGood
GROUP BY Number, Description
UNION
SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'Good' AS Description, COUNT(Description) AS
GradeCount, 4 AS OrderBy
FROM vQualScoringGood AS vQualScoringGood
GROUP BY Number, Description
UNION
SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'Satisfactory' AS Description, COUNT(Description) AS
GradeCount, 5 AS OrderBy
FROM vQualScoringSatisfactory AS vQualScoringSatisfactory
GROUP BY Number, Description
UNION
SELECT CASE CHARINDEX('.', Number) WHEN 0 THEN Number ELSE
REPLACE(LEFT(Number, CHARINDEX('.', Number)), '.', '')
END AS Period, 'Unsatisfactory' AS Description, COUNT(Description) AS
GradeCount, 6 AS OrderBy
FROM vQualScoringUnsatisfactory AS vQualScoringUnsatisfactory
GROUP BY Number, Description) AS QualScoringGrade
ORDER BY OrderBy
I am guessing that the problem is due to the OrderBy column in your PIVOT query. This line is the cause of your problem:
SELECT Period, Description, Value, OrderBy
I would alter the query to be:
SELECT #cols = STUFF((SELECT '],[' + [Description]
FROM vQualScoringGrade
GROUP BY [Description]
ORDER BY MAX([orderby]), [Description]
FOR XML PATH('')), 1,2,'') + ']'
SET #query = N'SELECT Period, ' + #cols + '
FROM
(
SELECT Period, Description, Value
FROM vQualScoringGrade
) p
PIVOT
(
SUM([Value])
for [Description] IN ( ' + #cols + ' )
) AS pvt
ORDER BY Period'
execute(#query);
The OrderBy column is not being used in the outer select or the PIVOT but you include it in the subquery. This column is being used in the grouping that takes place during a PIVOT. If the values are distinct, then you will get multiple rows.
You can easily test this by including the OrderBy on the final select list.
Related
I am trying to create pivot where row is Brand and SKU, sum is qty for column YYMM, but I'm not sure why it is throwing an error. Please help.
Code:
DECLARE #TABLE TABLE
(
SKU VARCHAR(10),
YYMM VARCHAR(50),
BRAND VARCHAR(50),
QTY INT
)
INSERT INTO #TABLE
SELECT '104591168', '2015-January', 'abott', 2 UNION ALL
SELECT '104580709', '2016-January', 'GSK', 2 UNION ALL
SELECT '104720038', '2017-January', 'RANBAXCY', 2 UNION ALL
SELECT '10467011A', '2018-January', 'abott', 2 UNION ALL
SELECT '104590691', '2019-January', 'abott', 10
Pivot code:
select *
from
(select
BRAND, sku, QTY, YYMM
from #TABLE) src
pivot
(sum(QTY)
for [Year Month]
You forgot to finish your query.
Please see the bottom of MSDN article for PIVOT examples.
I would guess that you wanted your query to look something like this:
SELECT *
FROM(
SELECT BRAND, sku, QTY, YYMM
FROM #TABLE
) AS src
PIVOT(
sum(QTY)
for [YYMM] IN( [2015-January], [2016-January], [2017-January] /* add other moneths here */ )
) AS Pivoted
We can make it as Dynamic sql
DECLARE #Column NVARCHAR(max),
#Column2 NVARCHAR(max),
#Sql NVARCHAR(max)
SELECT #Column = Stuff((SELECT DISTINCT ', '
+ Quotename(Cast(yymm AS VARCHAR(20)))
FROM #table
FOR xml path ('')), 1, 1, '')
SELECT #Column2 = Stuff((SELECT DISTINCT ', ' + 'ISNULL('
+ Quotename(Cast(yymm AS VARCHAR(20)))
+ ','
+ '''0''' + ') AS '
+ Quotename(Cast(yymm AS VARCHAR(20)))
FROM #table
FOR xml path ('')), 1, 1, '')
SET #Sql='
SELECT BRAND ,sku,'+#Column2+'
FROM(
SELECT *
FROM #TABLE
) AS src
PIVOT(
sum(QTY)
for [YYMM] IN('+#Column+')
) AS Pivoted
'
PRINT #Sql
EXEC(#Sql)
Result
BRAND sku 2015-January 2016-January 2017-January 2018-January 2019-January
--------------------------------------------------------------------------------------------------------
abott 104590691 0 0 0 0 10
abott 104591168 2 0 0 0 0
abott 10467011A 0 0 0 2 0
GSK 104580709 0 2 0 0 0
RANBAXCY 104720038 0 0 2 0 0
I am using sql server 2012 and I have a table like this:
FieldName FieldValue
DivisionId 1
DivisionId 2
DivisionId 3
CompanyId 2
CompanyId 3
LocationId 1
What i want is concatenate columns and form a where clause query like this
(DivisionId=1 OR DivisionId=2 OR DivisionId=3) AND
(CompanyId=2 OR CompanyId=3) AND
(LocationId = 1)
What I was able to figure out is, I need to concatenate columns values like this
DECLARE #Query VARCHAR(MAX)
SELECT #Query =
ISNULL(#Query,'') + IIF(#Query IS NOT NULL, ' AND ', '') + CONCAT(DF.FieldName,'=',DA.FieldValue)
FROM TABLE
SELECT #Query;
But this code will not handle OR condition.
Try following solution:
DECLARE #eav TABLE (
FieldName NVARCHAR(128) NOT NULL,
FieldValue VARCHAR(50) NOT NULL
)
INSERT #eav (FieldName, FieldValue)
SELECT 'DivisionId', 1 UNION ALL
SELECT 'DivisionId', 2 UNION ALL
SELECT 'DivisionId', 3 UNION ALL
SELECT 'CompanyId ', 2 UNION ALL
SELECT 'CompanyId ', 3 UNION ALL
SELECT 'LocationId', 1
DECLARE #Predicate NVARCHAR(MAX) = N''
SELECT #Predicate = #Predicate
+ CASE WHEN rn_asc = 1 THEN ' AND ' + FieldName + ' IN (' + LTRIM(FieldValue) ELSE '' END
+ CASE WHEN rn_asc > 1 THEN ', ' + LTRIM(FieldValue) ELSE '' END
+ CASE WHEN rn_desc = 1 THEN ') ' ELSE '' END
FROM (
SELECT *,
rn_asc = ROW_NUMBER() OVER(PARTITION BY x.FieldName ORDER BY x.FieldValue),
rn_desc= ROW_NUMBER() OVER(PARTITION BY x.FieldName ORDER BY x.FieldValue DESC)
FROM #eav x
) y
ORDER BY FieldName, FieldValue
SELECT #Predicate = STUFF(#Predicate, 1, 5, '')
SELECT #Predicate
-- Results: CompanyId IN (2, 3) AND DivisionId IN (1, 2, 3) AND LocationId IN (1)
Then you could use #Predicate to create a dynamic SQL SELECT statement (for example)
DECLARE #SqlStatement NVARCHAR(MAX)
SET #SqlStatement = 'SELECT ... FROM dbo.Table1 WHERE ' + #Predicate
EXEC sp_executesql #SqlStatement
I want to use Pivot to convert rows to columns.
I have three tables:
Student table with columns StudentID and StudentName
Subject table with columns SubjectID and SubjectName
Student Subject table with columns StudentSubjectID, StudentID, SubjectID and Date
Now I wrote a query to get data from the above tables
StudentID StudentName SubjectID SubjectName DateTime
-----------------------------------------------------------
1 Yasser 1 Math 1/1/2017
1 Yasser 1 English 1/1/2017
1 Yasser 1 Math 3/1/2017
1 Mark 1 Math 1/1/2017
1 John 1 Math 6/1/2017
Now I will make a monthly report to display Student Subject per month and output should be
Student/Days 1/1/2017 2/1/2017 3/1/2017 4/1/2017 ......................................... 30/1/2017 (All days for month)
Yasser Math - Math - -
English - - - -
Mark Math - - - -
How can I do this?
Thank you
I guess the script will require too complex dynamic coding,
I had just created a schema but will take too much effort to convert for a complete dynamic SQL script
;with cte as (
select distinct StudentName, SubjectName, [DateTime] from studentCTE
), cte2 as (
select
StudentName,
case when [DateTime] = '2017-01-01' then SubjectName else null end as '2017-01-01',
case when [DateTime] = '2017-03-01' then SubjectName else null end as '2017-03-01',
case when [DateTime] = '2017-06-01' then SubjectName else null end as '2017-06-01'
from cte
)
SELECT distinct
StudentName,
STUFF(
(
SELECT
',' + [2017-01-01]
FROM cte2 C
where c.StudentName = cte2.StudentName
FOR XML PATH('')
), 1, 1, ''
) As '2017-01-01',
STUFF(
(
SELECT
',' + [2017-03-01]
FROM cte2 C
where c.StudentName = cte2.StudentName
FOR XML PATH('')
), 1, 1, ''
) As '2017-03-01',
STUFF(
(
SELECT
',' + [2017-06-01]
FROM cte2 C
where c.StudentName = cte2.StudentName
FOR XML PATH('')
), 1, 1, ''
) As '2017-06-01'
from cte2
I hope it helps somehow,
But I guess after SQL concatenation of subjectname fields, the below query can be solved by a dynamic sql pivot
Please check following dynamic SQL pivot query
DECLARE #PivotColumnHeaders VARCHAR(MAX)
SELECT #PivotColumnHeaders =
COALESCE(
#PivotColumnHeaders + ',[' + convert(nvarchar(20),date,23) + ']',
'[' + convert(nvarchar(20),date,23) + ']'
)
FROM dbo.GetFullMonth(getdate())
DECLARE #PivotTableSQL NVARCHAR(MAX)
SET #PivotTableSQL = N'
SELECT *
FROM (
select distinct StudentName,
STUFF(
(
SELECT
'','' + SubjectName
FROM studentCTE C
where c.StudentName = studentCTE.StudentName
and c.DateTime = studentCTE.DateTime
FOR XML PATH('''')
), 1, 1, ''''
) As Subjects
, [DateTime]
from studentCTE
) AS PivotData
PIVOT (
MAX(Subjects)
FOR [DateTime] IN (
' + #PivotColumnHeaders + '
)
) AS PivotTable
'
EXECUTE(#PivotTableSQL)
Here is my output
To summarize the query, first of all I need the current month's dates as column names. I used the calendar function module GetFullMonth at given reference. I just changed the return "datetime" column to "date" data type.
As I noted in my previous code sample, I used SQL concatenation with FOR XML PATH method.
One last reference I'ld like to share with you. I used date to string conversion in the PivotColumnHeaders section of the dynamic query where I define the additional pivot columns. I used the conversion parameter as 23.
You can check for a full list of datetime format parameter at given reference.
I hope these helps you for the solution,
If you want to date column contains only what has your table, then you have to use this query.
DECLARE #DYNQRY AS VARCHAR(MAX)
,#COL AS VARCHAR(MAX)
SELECT #COL= ISNULL(#COL + ',','')
+ QUOTENAME(DATE)
FROM (SELECT DISTINCT DATE FROM STUDENTSUBJECT) AS DATE
SET #DYNQRY ='SELECT STUDENTNAME, ' + #COL + '
FROM (SELECT A.STUDENTID,STUDENTNAME,SUBJECTNAME,DATE
FROM STUDENT A,SUBJECT B,STUDENTSUBJECT C
WHERE A.STUDENTID=C.STUDENTID
AND B.SUBJECTID=C.SUBJECTID
)A
PIVOT(
MAX(SUBJECTNAME)
FOR DATE IN (' + #COL + ')
) AS PVTTABLE'
EXEC (#DYNQRY)
CREATE TABLE #tt(StudentID INT,StudentName VARCHAR(200),SubjectID INT,SubjectName VARCHAR(200),[DateTime]DATETIME)
INSERT INTO #tt
SELECT 1,'Yasser',1,'Math','01/01/2017' UNION
SELECT 1,'Yasser',1,'English','01/01/2017' UNION
SELECT 1,'Yasser',1,'Math','01/03/2017' UNION
SELECT 1,'Mark',1,'Math','01/01/2017' UNION
SELECT 1,'John',1,'Math','01/06/2017'
DECLARE #col1 VARCHAR(max),#col2 VARCHAR(max),#sql VARCHAR(max)
SELECT #col1=ISNULL(#col1+',','')+ t.d
,#col2=ISNULL(#col2+',','')+'ISNULL('+ t.d +',''-'') AS '+t.d
FROM #tt
INNER JOIN master.dbo.spt_values AS sv ON sv.type='P' AND sv.number BETWEEN 0 AND 30
CROSS APPLY(VALUES('['+CONVERT(VARCHAR,DATEADD(dd,sv.number,DATEADD(MONTH, MONTH([DateTime])-1,DATEADD(YEAR,YEAR([DateTime])-1900,0))),110)+']')) t(d)
WHERE MONTH(DATEADD(dd,sv.number,DATEADD(MONTH, MONTH([DateTime])-1,DATEADD(YEAR,YEAR([DateTime])-1900,0))))= MONTH([DateTime])
GROUP BY MONTH([DateTime]),YEAR([DateTime]),sv.number,t.d
PRINT #col2
SET #sql='
SELECT StudentID,StudentName,'+#col2+' FROM #tt
PIVOT(max(SubjectName) FOR [DateTime] IN ('+#col1+')) p'
EXEC (#sql)
--partial column--
StudentID StudentName 01-01-2017 01-02-2017 01-03-2017 01-04-2017 01-05-2017 01-06-2017 01-07-2017 01-08-2017 01-09-2017 01-10-2017 01-11-2017
1 John - - - - - Math - - - - -
1 Mark Math - - - - - - - - - -
1 Yasser Math - Math - - - - - - - -
i have a table like following
RequestNo Facility status
1 BDC1 Active
1 BDC2 Active
1 BDC3 Active
2 BDC1 Active
2 BDC2 Active
i want like this
RequestNo Facilty Count
1 BDC (1,2,3) 1
2 BDC(1,2) 1
the count should display based on Status with facilty.Fcilityv should take as BDC only
Try this, (assuming that your facility is fixed 4 character code)
SELECT RequestNo, Fname + '(' + FnoList + ')' Facilty, count(*) cnt
FROM
(
SELECT distinct RequestNo,
SUBSTRING(Facility,1,3) Fname,
stuff((
select ',' + SUBSTRING(Facility,4,4)
from Dummy
where RequestNo = A.RequestNo AND
SUBSTRING(Facility,1,3) = SUBSTRING(A.Facility,1,3)
for xml path('')
) ,
1, 1, '') as FnoList
FROM Dummy A
) x
group by RequestNo, Fname, FnoList;
SQL DEMO
This doesn't put any constraints on the length of the Facility field. It strips out the chars from the beginning and the numeric numbers from the ending:
SELECT RequestNo, FacNameNumbers, COUNT(Status) as StatusCount
FROM
(
SELECT DISTINCT
t1.RequestNo,
t1.Status,
substring(facility, 1, patindex('%[^a-zA-Z ]%',facility) - 1) +
'(' +
STUFF((
SELECT DISTINCT ', ' + t2.fac_number
FROM (
select distinct
requestno,
substring(facility, 2 + len(facility) - patindex('%[^0-9 ]%',reverse(facility)), 9999) as fac_number
from facility
) t2
WHERE t2.RequestNo = t1.RequestNo
FOR XML PATH (''))
,1,2,'') + ')' AS FacNameNumbers
FROM Facility t1
) final
GROUP BY RequestNo, FacNameNumbers
And the SQL Fiddle
I have a database in the following format:
ID TYPE SUBTYPE COUNT MONTH
1 A Z 1 7/1/2008
1 A Z 3 7/1/2008
2 B C 2 7/2/2008
1 A Z 3 7/2/2008
Can I use SQL to convert it into this:
ID A_Z B_C MONTH
1 4 0 7/1/2008
2 0 2 7/2/2008
1 0 3 7/2/2008
So, the TYPE, SUBTYPE are concatenated into new columns and COUNT is summed where the ID and MONTH match.
Any tips would be appreciated. Is this possible in SQL or should I program it manually?
The database is SQL Server 2005.
Assume there are 100s of TYPES and SUBTYPES so and 'A' and 'Z' shouldn't be hard coded but generated dynamically.
SQL Server 2005 offers a very useful PIVOT and UNPIVOT operator which allow you to make this code maintenance-free using PIVOT and some code generation/dynamic SQL
/*
CREATE TABLE [dbo].[stackoverflow_159456](
[ID] [int] NOT NULL,
[TYPE] [char](1) NOT NULL,
[SUBTYPE] [char](1) NOT NULL,
[COUNT] [int] NOT NULL,
[MONTH] [datetime] NOT NULL
) ON [PRIMARY]
*/
DECLARE #sql AS varchar(max)
DECLARE #pivot_list AS varchar(max) -- Leave NULL for COALESCE technique
DECLARE #select_list AS varchar(max) -- Leave NULL for COALESCE technique
SELECT #pivot_list = COALESCE(#pivot_list + ', ', '') + '[' + PIVOT_CODE + ']'
,#select_list = COALESCE(#select_list + ', ', '') + 'ISNULL([' + PIVOT_CODE + '], 0) AS [' + PIVOT_CODE + ']'
FROM (
SELECT DISTINCT [TYPE] + '_' + SUBTYPE AS PIVOT_CODE
FROM stackoverflow_159456
) AS PIVOT_CODES
SET #sql = '
;WITH p AS (
SELECT ID, [MONTH], [TYPE] + ''_'' + SUBTYPE AS PIVOT_CODE, SUM([COUNT]) AS [COUNT]
FROM stackoverflow_159456
GROUP BY ID, [MONTH], [TYPE] + ''_'' + SUBTYPE
)
SELECT ID, [MONTH], ' + #select_list + '
FROM p
PIVOT (
SUM([COUNT])
FOR PIVOT_CODE IN (
' + #pivot_list + '
)
) AS pvt
'
EXEC (#sql)
select id,
sum(case when type = 'A' and subtype = 'Z' then [count] else 0 end) as A_Z,
sum(case when type = 'B' and subtype = 'C' then [count] else 0 end) as B_C,
month
from tbl_why_would_u_do_this
group by id, month
You change requirements more than our marketing team! If you want it to be dynamic you'll need to fall back on a sproc.