I have query:
SELECT DISTINCT temp.ID,request.RequestTypeID
FROM #MyTempTable6 as temp
JOIN dbo.FingerMachineUsers as fingeruser
ON temp.UserNo = fingeruser.ID
JOIN dbo.AppUsers as appuser
ON appuser.Id = fingeruser.UserId
LEFT JOIN dbo.Requests as request
ON request.UserId = fingeruser.UserId
And result of it:
How can I create table like this:
ID|RequestTypeID1|RequestTypeID2
1 | 4| 5
If you have only two values, then the simplest method is aggregation:
SELECT t.ID, MIN(r.RequestTypeID), MAX(r.RequestTypeID)
FROM #MyTempTable6 t JOIN
dbo.FingerMachineUsers fu
ON t.UserNo = fu.ID JOIN
dbo.AppUsers au
ON au.Id = fu.UserId LEFT JOIN
dbo.Requests r
ON r.UserId = fu.UserId
GROUP BY t.ID;
If you have have a variable number of values that you want to present, then the query is much more complicated.
PIVOT operator could be your best friend, if there are always only 2 values each...
Try this query...
Disclaimer: This code is purely based on this answer. (https://stackoverflow.com/a/10404455/6327676)
DECLARE #cols AS NVARCHAR(max),
#query AS NVARCHAR(max);
SET #cols = Stuff((SELECT DISTINCT ',' + Quotename(stff.requesttypeid)
FROM TableName stff
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, ''
)
SET #query = 'SELECT ID, '+ #cols
+ ' FROM (select ID, RequestTypeId FROM TableName) x pivot (MAX(RequestTypeId) FOR RequestTypeId in ('
+ #cols + ')) p'
EXECUTE(#query)
Try this code it will work according to the result you want.
Firstly you need to dump #MyTempTable6 table into #temptable
then set RequestTypeID columns as comma seperated in #colums varible then set the columnname in #Requestcolumns variable,Then use pivot.
DECLARE #colums AS NVARCHAR(max)
DECLARE #Requestcolumns AS NVARCHAR(max)
DECLARE #query AS NVARCHAR(max);
SELECT DISTINCT temp.ID,request.RequestTypeID
into #temptable
FROM #MyTempTable6 as temp
JOIN dbo.FingerMachineUsers as fingeruser
ON temp.UserNo = fingeruser.ID
JOIN dbo.AppUsers as appuser
ON appuser.Id = fingeruser.UserId
LEFT JOIN dbo.Requests as request
ON request.UserId = fingeruser.UserId
SET #colums = Stuff((SELECT DISTINCT ',' +Quotename(tab.RequestTypeID)
FROM #temptable tab
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, ''
)
SET #Requestcolumns = Stuff((SELECT DISTINCT ',' +Quotename(tab.RequestTypeID) +' AS ',+Quotename('RequestTypeID'+CONVERT(varchar(100),tab.RequestTypeID))
FROM #temptable tab
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, ''
)
SET #query = 'SELECT ID, '+#Requestcolumns
+ ' FROM (select ID, RequestTypeID FROM #temptable) x pivot (MAX(RequestTypeID) FOR RequestTypeID in ('
+ #colums + ')) p'
EXECUTE(#query)
DROP table #temptable
Related
I need to Pivot Questions With Their Answers.The Desired Output of the pivot Query is below and the table structure too.
I have Created the SQL fiddle Here Sql Fiddle. I saw many examples of count with pivot but couldn't find something similar to this.
You simply need some joins to get the base data and a dynamic pivot to show the result in the desired format.
try the following:
drop table if exists #temp
--base table with all details
select s.ID SurveyID, s.SubmittedBy, sq.Question, sa.Answer
into #temp
from #Survey s
join #SurveyMaster sm on sm.ID = s.SurveyMasterID
join #SurveyQuestion sq on sq.SurveyMasterID = s.SurveyMasterID
join #SurveyAnswers sa on sa.SurveyQuestionID = sq.ID and sa.SurveyID = s.ID
--dynamic pivot
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Question)
FROM #temp c
ORDER BY 1 DESC
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT SurveyID, SubmittedBy, ' + #cols + ' from
(
select SurveyID, SubmittedBy, Question, Answer
from #temp
) x
pivot
(
max(Answer)
for Question in (' + #cols + ')
) p '
--execution
execute(#query)
Please find the db<>fiddle here.
declare #sqlstring as varchar(max) = '';
SELECT
#sqlstring = STUFF((
SELECT distinct
',' + '[' + isnull(sq.Question, '''') + ']'
from
#surveyanswers sa
join
#SurveyQuestion sq
on sq.ID = sa.SurveyQuestionID
join
#survey sv
on sv.SurveyMasterID = sq.SurveyMasterID FOR XML PATH('')), 1, 1, '')
select
sa.SurveyID,
sv.SubmittedBy,
sq.Question,
sa.Answer into ##temp
from
#surveyanswers sa
join
#SurveyQuestion sq
on sq.ID = sa.SurveyQuestionID
join
#survey sv
on sv.SurveyMasterID = sq.SurveyMasterID
set
#sqlstring = 'SELECT SurveyID,SubmittedBy,' + #sqlstring + ' FROM (select * from ##temp ) t ' + ' PIVOT ( ' + ' max(Answer) FOR Question IN (' + #sqlstring + ' ) ) AS pivot_table' execute(#sqlstring);
RESULT:
Can someone help me how I can rewrite this query to get following result.
1 2 3 4 5
U.T A.H E.Z R.Z S.A
Sometimes it will return more or less than 5 results.
My query:
SELECT
LEFT(a.Vorname, 1) + '.' + LEFT(a.Name, 1) AS Name
FROM
ADR_Adressen a
LEFT JOIN
ADR_GruppenLink gl ON gl.AdressNrADR = a.AdressNrADR
WHERE
a.Z_Klasse = 'BA' AND gl.GruppeADR != 'KIND'
this could help you, using ROW_NUMBER()
DECLARE #cols AS NVARCHAR(MAX)
SELECT #cols = STUFF((SELECT ',[' + convert(varchar,ROW_NUMBER() OVER ( ORDER BY LEFT(a.[Name],1) ) )+ ']' AS ID
FROM [ADR_Adressen] a
FOR XML PATH(''), TYPE).value('.', 'varchar(max)'),1,1, '')
DECLARE #query AS NVARCHAR(MAX);
SET #query = N'SELECT ' + #cols + N' from
(
SELECT ROW_NUMBER() OVER ( ORDER BY LEFT(a.Name,1) ) AS ID,
LEFT(vorname,1) + ''.'' + LEFT(Name,1) Name
from ADR_Adressen a
LEFT JOIN ADR_GruppenLink gl ON gl.AdressNrADR = a.AdressNrADR
WHERE a.Z_Klasse = 'BA' AND gl.GruppeADR != 'KIND'
) x
pivot
(
max(Name)
for ID in (' + #cols + N')
) p
'
exec sp_executesql #query;
There's no pretty way to do this, if the number of rows is variable.
Building heavily on the answer to this question, you need to dynamically build the query before executing it.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
-- Build a list of ids for each of the selected rows
SELECT #cols = STUFF((SELECT ',[' + convert(varchar,ROW_NUMBER() OVER ( ORDER BY LEFT([vorname],1),LEFT([Name],1) ) ) + ']'
FROM #ADR_Adressen
LEFT JOIN ADR_GruppenLink gl ON gl.AdressNrADR = a.AdressNrADR
WHERE a.Z_Klasse = 'BA' AND gl.GruppeADR != 'KIND'
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
-- Build a query using the list of IDs selected above. These are pivotted into column names
set #query = N'SELECT ' + #cols + N' from
(
select
ROW_NUMBER() OVER ( ORDER BY LEFT([vorname],1),LEFT([Name],1) ) ID,
LEFT(vorname,1) + ''.'' + LEFT(Name,1) Name
from #ADR_Adressen a
LEFT JOIN ADR_GruppenLink gl ON gl.AdressNrADR = a.AdressNrADR
WHERE a.Z_Klasse = 'BA' AND gl.GruppeADR != 'KIND'
) x
pivot
(
max(Name)
for ID in (' + #cols + N')
) p
'
exec sp_executesql #query;
Updated: Given that no ID field is available I've updated this to incorporate the ROW_NUMBER suggestion from Alex below
Query example
I know there are better ways to design the table but this is just an example of what I need
I just can't seem to get the results I'm looking for
Table and data:
Query:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
SET #cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(columnType)
FROM [Values]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #query = 'SELECT ' + #cols + ' FROM
(
SELECT value, columnType
FROM [Values]
) x
PIVOT
(
MAX(value)
FOR columnType IN (' + #cols + ')
) p '
EXECUTE(#query)
Result I get:
Results I want
Product Item SubItem
A A A A A A
A A B A A B
B B A NULL
Your query can be easily resolved using joins for two levels:
select v.value as Product, vi.value as Item, vsi.value as Subitem
from [Values] v left join
[Values] vi
on vi.column_type = 'Item' and vi.parent_id = v.id left join
[Values] vsi
on vsi.column_type = 'Sub Item' and vsi.parent_id = v.id
where v.column_type = 'Product';
If you have an unknown number of levels, then you can expand on this query using dynamic SQL.
To avoid "ORDER BY items must appear in the select list if SELECT DISTINCT is specified.", I need to add AssessmentSuperSet.Deadline to my SELECT statement at the top. Where should I do this? Any help greatly appreciated. Thanks.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF(
(SELECT distinct ',' + QUOTENAME(AssessmentSuperSet.Title)
from AssessmentSuperSet inner join AssessmentSet on AssessmentSuperSet.SuperSetID = AssessmentSet.SuperSetID
where ClassID = '8KF/En 14/15' order by AssessmentSuperSet.Deadline ASC
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT StudentID, FName, SName, ' + #cols + ' from
(
select KS3Assessments.StudentID,
Pupils.FName,
Pupils.SName,
KS3Assessments.NCLevel,
AssessmentSuperSet.Title
from KS3Assessments inner join Pupils on KS3Assessments.StudentID = Pupils.StudentID
inner join AssessmentSuperSet on KS3Assessments.SuperSetID = AssessmentSuperSet.SuperSetID
where Pupils.GroupDesignation = ''8KF/En 14/15''
) x
pivot (max(NCLevel) for Title in (' + #cols + ') ) p '
execute(#query)
Instead of distinct try using a group by clause:
select #cols = STUFF(
(SELECT ',' + QUOTENAME(AssessmentSuperSet.Title)
from AssessmentSuperSet inner join AssessmentSet on AssessmentSuperSet.SuperSetID = AssessmentSet.SuperSetID
where ClassID = '8KF/En 14/15'
group by AssessmentSuperSet.title, AssessmentSuperSet.Deadline
order by AssessmentSuperSet.Deadline ASC
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT StudentID, FName, SName, ' + #cols + ' from
(
select KS3Assessments.StudentID,
Pupils.FName,
Pupils.SName,
KS3Assessments.NCLevel,
AssessmentSuperSet.Title
from KS3Assessments inner join Pupils on KS3Assessments.StudentID = Pupils.StudentID
inner join AssessmentSuperSet on KS3Assessments.SuperSetID = AssessmentSuperSet.SuperSetID
where Pupils.GroupDesignation = ''8KF/En 14/15''
) x
pivot (max(NCLevel) for Title in (' + #cols + ') ) p '
execute(#query)
Since you didn't provide any suitable test data I haven't tried it.
select *
from (
select vtid, convert(date, dtime) as Date from Transaction_tbl where locid = 5
) as vt
pivot (
count(vtid)
for vtid in (select vtid from VType_tbl)
) as pvt
while executing this query am getting error
Incorrect syntax near the keyword 'select'." and Incorrect syntax near
')'.
actually I have one more table,name= Vtype_table , How Can I load all vtid from vtype table in this query? I want to get output depend upon vtid.
Any help greatly appreciated.
Your PIVOT syntax is correct except you are using a SELECT statement inside your PIVOT.
You cannot use a SELECT statement inside the PIVOT IN clause to select column headers. It is required that the columns for the IN clause be known prior to executing the query.
If you are looking to generate a dynamic list of vtid values, then you will need to use dynamic SQL to get the result and the syntax will be similar to the following:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(vtid)
from VType_tbl
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT Date, ' + #cols + '
from
(
select vtid, convert(date, dtime) as Date
from Transaction_tbl
where locid = 5
) d
pivot
(
count(vtid)
for vtid in (' + #cols + ')
) p '
execute(#query);
Edit, if you want the type names to appear then you should be able to use the following:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(vt_name)
from VType_tbl
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT Date, ' + #cols + '
from
(
select v.vt_name, convert(date, dtime) as Date
from Transaction_tbl t
inner join VType_tbl v
on t.vtid = v.vtid
where locid = 5
) d
pivot
(
count(vt_name)
for vt_name in (' + #cols + ')
) p '
execute(#query)
Note: I am guessing on the column name for VType_tbl