SQL Dynamic Pivot Query - sql

I need help with a pivot table if possible. Not sure it can be done. Below is my example.
Questions
Answers
User Answers
Answer Pivot
Thanks For any help.
I have attached a screenshot of db results with the pivot working . The code below pivot as it should and that works fine. If you can look at the column "Subject has exp..." I would like the column repeated three times, The heading is the question, But I also would like each possible answer to shown with the question as well.
Thank Again!
Thansk Again.
Here Is a Sample of the Code:
DECLARE #columns VARCHAR(MAX)
SELECT #columns = COALESCE(#columns + ','+QUOTENAME([QuestionText]),QUOTENAME([QuestionText]))
FROM SchemaWema.vts_vwSurvey INNER JOIN
Question ON SchemaWema.vts_vwSurvey.SurveyID = SchemaWema.vts_vwQuestion.SurveyID
WHERE SchemaWema.vts_vwSurvey.DecisionSetId = 598 AND SchemaWema.vts_vwSurvey.FormType = 1
Set #columns = REPLACE(#columns, '[]', '[No Name Given]')
DECLARE #sql NVARCHAR(MAX)=N' SELECT * FROM
(
SELECT Project.PROJECTNAME, Project.ID,
Sites.PROJECTSTUDYSITENUMBER, Sites.PROJECTSTUDYSITENAME,
Study.PROJECTSTUDYNAME, Study.PROJECTSTUDYNUMBER,
Survey.SurveyID, Question.QuestionID, Cases.SITEID, Cases.EVENTDATE,
Cases.SUBJNO, Cases.EventType, Cases.TriggerEvent,
Cases.DecisionSetID, Cases.PanelID, Cases.RECORDSTATUS,
Project.PROJECTSPONSOR, VoterAnswers.AnswerID, VoterAnswers.VoterID,
VoterAnswers.AnswerText AS FreeTypedAnswers, Voter.VoteDate, Users.SHOWNNAME, Panel.PANELNAME, Sites.COUNTRY,
Cases.VERSIONID, cases.CSID, cases.CASENUMBER,Cases.CASEDATEUPDATED AS LASTUPDATED,
Cases.DECISIONSETNAME,
Question.QuestionText,
CASE
WHEN
CAST(VoterAnswers.AnswerText AS VARCHAR(MAX)) IS NULL OR CAST(VoterAnswers.AnswerText AS VARCHAR(MAX)) = ''''
THEN
Answer.AnswerText
ELSE
CAST(Answer.AnswerText AS VARCHAR(MAX))
END AS AnswerText
FROM
(
SELECT a.ID, a.STUDYID, a.SITEID, a.CSID, a.VERSIONID, a.CASENUMBER, a.CASEINITIALS, a.EVENTDATE, a.CASEDETAILSFILE, a.CASEDETAILSFILEVERSION,
a.CASESTATUS, a.RECORDSTATUS, a.CASEDATEUPDATED, a.PROJECTDATEUPDATED, a.PanelID, a.DecisionSetID, a.SUBJNO, a.EventType, a.TriggerEvent,
a.Priority, a.id1, a.id2, a.dateid, a.dateiddt1, a.dateiddt2, a.extratext1, a.extratext2, SchemaWema.PROJECTPANELDECISIONSETVIEW.DECISIONSETNAME
FROM SchemaWema.PROJECTCASE AS a LEFT OUTER JOIN
SchemaWema.PROJECTPANELDECISIONSETVIEW ON a.DecisionSetID = SchemaWema.PROJECTPANELDECISIONSETVIEW.DECISIONSETID
WHERE (a.CASEDATEUPDATED =
(SELECT MAX(CASEDATEUPDATED) AS Expr1
FROM SchemaWema.PROJECTCASE AS b
WHERE (a.ID = PROJECTID) AND (a.CSID = CASEID) AND (a.VERSIONID = VERSIONID) )) AND (a.RECORDSTATUS <> ''D'')
)Cases
LEFT OUTER JOIN
(
SELECT PROJECTID, PROJECTNAME, PROJECTSPONSOR
FROM SchemaWema.PROJECT AS a
WHERE (PROJECTDATEUPDATED =
(SELECT MAX(PROJECTDATEUPDATED) AS Expr1
FROM SchemaWema.PROJECT AS b
WHERE (a.ID = PROJECTID))) AND (RECORDSTATUS <> ''D'')
) Project on
Project.ID = Cases.ID
LEFT OUTER JOIN
(
SELECT DISTINCT a.ID, a.STUDYID, a.SITEID, a.PROJECTSTUDYSITENAME, a.PROJECTSTUDYSITENUMBER, SchemaWema.PROJECTSTUDYVIEW.PROJECTSTUDYNAME, a.COUNTRY
FROM SchemaWema.PROJECTSTUDYSITE AS a INNER JOIN
SchemaWema.PROJECTVIEW ON a.ID = SchemaWema.PROJECTVIEW.ID INNER JOIN
SchemaWema.PROJECTSTUDYVIEW ON a.ID = SchemaWema.PROJECTSTUDYVIEW.ID AND
a.STUDYID = SchemaWema.PROJECTSTUDYVIEW.STUDYID
WHERE (a.PROJECTSTUDYSITEDATEUPDATED =
(SELECT MAX(PROJECTSTUDYSITEDATEUPDATED) AS Expr1
FROM SchemaWema.PROJECTSTUDYSITE AS b
WHERE (a.ID = PROJECTID) AND (a.STUDYID = STUDYID) AND (a.SITEID = SITEID))) AND (a.RECORDSTATUS <> ''D'')
)Sites on
Cases.SITEID = Sites.SITEID
LEFT OUTER JOIN
(
SELECT DISTINCT PROJECTID, STUDYID, PROJECTSTUDYNAME, PROJECTSTUDYNUMBER, PROJECTSTUDYDESCRIPTION
FROM SchemaWema.PROJECTSTUDY AS a
WHERE (PROJECTSTUDYDATEUPDATED =
(SELECT MAX(PROJECTSTUDYDATEUPDATED) AS Expr1
FROM SchemaWema.PROJECTSTUDY AS b
WHERE (a.ID = PROJECTID) AND (ISNULL(a.STUDYID, ''0'') = ISNULL(STUDYID, ''0'')))) AND (RECORDSTATUS <> ''D'')
)Study on
Study.STUDYID = Cases.STUDYID
inner join
(
SELECT VoterID, UID, SurveyID, ContextUserName, VoteDate, StartDate, IPSource, Validated, ResumeUID, ResumeAtPageNumber, ProgressSaveDate,
ResumeQuestionNumber, ResumeHighestPageNumber, LanguageCode, SurveyStatus, VoteAcceptRejectDate, CaseID, VersionID, PdfFileName, voterSurveyStatus,
dateupdated, recordstatus, modifiedby, changereason
FROM SchemaWema.vts_tbVoter AS a
WHERE (dateupdated =
(SELECT MAX(dateupdated) AS Expr1
FROM SchemaWema.vts_tbVoter AS b
WHERE (a.VoterID = VoterID) AND (a.SurveyID = SurveyID) AND (a.CSID = CaseID) AND (a.VersionID = VersionID)))
) Voter on
Voter.CSID = Cases.CSID
AND Voter.VersionID = Cases.VersionID
Inner Join
(
SELECT DISTINCT SurveyID, DecisionSetId, FormType
FROM SchemaWema.vts_tbSurvey AS a
WHERE (dateupdated =
(SELECT MAX(dateupdated) AS Expr1
FROM SchemaWema.vts_tbSurvey AS b
WHERE (a.SurveyID = SurveyID))) AND (recordstatus <> ''D'')
) Survey on
Survey.SurveyID = Voter.SurveyID
inner Join
(
SELECT DISTINCT
VoterID, AnswerID, SectionNumber, CAST(AnswerText AS varchar(MAX)) AnswerText, SurveyID, CaseID, versionID
FROM SchemaWema.vts_tbVoterAnswers AS a
WHERE (dateupdated =
(SELECT MAX(dateupdated) AS Expr1
FROM SchemaWema.vts_tbVoterAnswers AS b
WHERE (a.VoterID = VoterID) AND (a.AnswerID = AnswerID) AND (a.SectionNumber = SectionNumber) AND (a.SurveyID = SurveyID) AND (a.CSID = CaseID) AND
(a.versionID = versionID))) AND (recordstatus <> ''D'')
)VoterAnswers on
VoterAnswers.SurveyID = Survey.SurveyID
AND VoterAnswers.CSID = Voter.CSID
AND Voter.VoterID = VoterAnswers.VoterID
AND VoterAnswers.versionID = Voter.versionID
AND VoterAnswers.SurveyID = Voter.SurveyID
FULL OUTER JOIN
(
select DISTINCT a.USERID, a.USERNAME, a.FIRSTNAME, a.LASTNAME, a.SHOWNNAME
from SchemaWema.users as a
WHERE (a.userdateupdated =
(SELECT MAX(b.userdateupdated) AS Expr1
FROM SchemaWema.users AS b
WHERE (a.userID = b.userID) ))
AND (a.RECORDSTATUS <> ''D'')
) Users on
VoterAnswers.VoterID = Users.USERID
AND Voter.VoterID = Users.USERID
inner join
(
SELECT DISTINCT AnswerID, QuestionID, AnswerText FROM SchemaWema.vts_tbAnswer AS a
WHERE (dateupdated =
(SELECT MAX(dateupdated) AS Expr1
FROM SchemaWema.vts_tbAnswer AS b
WHERE (a.AnswerID = AnswerID))) AND (recordstatus <> ''D'')
) Answer on
Answer.AnswerID = VoterAnswers.AnswerID
inner Join
(
SELECT DISTINCT QuestionID,SurveyID, QuestionText
FROM SchemaWema.vts_tbQuestion AS a
WHERE (dateupdated =
(SELECT MAX(dateupdated) AS Expr1
FROM SchemaWema.vts_tbQuestion AS b
WHERE (a.QuestionID = QuestionID))) AND (recordstatus <> ''D'')
) Question on
Answer.QuestionID = Question.QuestionID
AND Question.SurveyID = Survey.SurveyID
AND Question.SurveyID = VoterAnswers.SurveyID
inner join
(
SELECT DIStinct
[PANELID] ,[PANELNAME]
FROM [AdjudicateV3].[Adjudicate].[PROJECTPANELVIEW]
)Panel on
Panel.PANELID = Cases.PanelID
WHERE CASEs.ID = ' + #ID + ' AND Survey.DecisionSetId = '+ DeeSetId +' AND Survey.FormType = '+ #Forms +'
) AS SourceTable
PIVOT
(
MAX(AnswerText)
FOR QuestionText IN ('+#columns+')
) AS PivotTable'

It can be done using a dynamic pivot.
First thing you have to do is build the cols you're going to use for the pivot..
declare #cols varchar(max)
select #cols = Coalesce(#cols + ', ', '') + '[' + q.Question + '(' + a.Question + ')]'
from Questions q
join Answers a on q.ID = a.QuestionID
this will concatenate all of the column headers you want into one string like
[What is your favorite Car Color(Blue)], [What is your favorite Car Color(Red)]
putting the column names inside brackets is important here...
The next step is building your pivot query
declare #sql varchar(max)
set #sql = 'Select [User], ' + #cols + ' from (
select ua.[User], ''X'' as Chosen,
q.Question + ''('' + a.Question + '')'' Answer
from UserAnswers ua
join Answers a On ua.AnswerId = a.ID and ua.QuestionID = a.QuestionID
join Questions q on a.QuestionID = q.ID
) t
pivot (
max(Chosen)
for Answer IN (' + #cols + ')
) p'
exec(#sql)
this will create a subquery with three columns User, Chose, Answer.. user is user name, chosen is just an X for every record, and the Answer, which is what is used to pivot. Answer looks like the column names above without the brackets..
next it pivots the subquery.. and selects the Name and dynamic columns..
SQL Fiddle Example

Related

Why is this SQL Server query so slow?

This query takes 4 seconds to run, and it returns about 62000 rows. #c, #p and #a are strings made up of ints, separated by commas or empty, based on what needs to be filtered... unfortunately this can't be changed.
I have tried to run this without the filters and it does not make a difference.
I am fairly new to SQL.
The 3 common table expressions are there to take extra lines of code out.
I would like this to be able to run under a second if at all possible
DECLARE #UId int = '817',
#c varchar(max) = '',
#p varchar(max) = '',
#a varchar(max) = ''
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
IF OBJECT_ID('tempdb..#FilteredData') IS NOT NULL
DROP TABLE #FilteredData;
WITH cteuag AS
(
SELECT
uag.CId,
uag.AuthorIsatIonGroupId,
rn = ROW_NUMBER() OVER (PARTITION BY uag.[UId], uag.CId, uag.AuthorIsatIonGroupId ORDER BY uag.CId)
FROM
uag
WHERE
uag.[UId] = #UId
AND uag.IsDeleted = 0
AND (#c = '' OR (#c LIKE CONVERT(varchar(4), uag.CId)
OR #c LIKE '%,' + CONVERT(varchar(4), uag.CId) + ',%'
OR #c LIKE CONVERT(varchar(4), uag.CId) + ',%'
OR #c LIKE '%,' + CONVERT(varchar(4), uag.CId))
)
),
cteuc AS
(
SELECT
uc.CId,
cteuag.AuthorIsatIonGroupId,
uc.[UId],
i.FirstName + Iif(i.MiddleName IS NOT NULL, ' ' + i.MiddleName + ' ', ' ') + i.Surname AS [AName],
rn = ROW_NUMBER() OVER (PARTITION BY uc.CId, uc.[UId] ORDER BY uc.ModifiedAt)
FROM
uc
INNER JOIN
cteuag ON cteuag.CId = uc.CId
AND uc.IsDeleted = 0
AND (#a = '' OR (#a LIKE CONVERT(varchar(4), uc.[UId])
OR #a LIKE '%,' + CONVERT(varchar(4), uc.[UId]) + ',%'
OR #a LIKE CONVERT(varchar(4), uc.[UId]) + ',%'
OR #a LIKE '%,' + CONVERT(varchar(4), uc.[UId]))
)
INNER JOIN
ui ON ui.[UId] = uc.[UId]
AND ui.IsDeleted = 0
INNER JOIN
i ON i.PId = ui.IndividualId
),
ctel AS
(
SELECT
la.LId,
p.CId,
la.[UId],
rn = ROW_NUMBER() OVER (PARTITION BY la.LId ORDER BY la.DateUpdated DESC)
FROM
la
INNER JOIN
p ON p.Id = la.PId
AND p.IsDeleted = 0
AND la.IsDeleted = 0
AND la.[UId] IS NOT NULL
INNER JOIN
l ON la.LId = l.Id
AND l.IsDeleted = 0
)
SELECT
c.Id AS CId,
c.[Name] AS CName,
u.Id AS AId,
cteuc.AName AS AName,
ctel.LId AS LId,
qh.Id AS QhId,
q.Id AS QId,
q.IsTrue AS isTrue,
p.Id AS PId,
p.[Name] AS PName,
qi.FinalCalculation AS Calculation
INTO
#FilteredData
FROM
c
INNER JOIN
cteuc ON cteuc.CId = c.Id
AND cteuc.Rn = 1
AND c.IsDeleted = 0
LEFT OUTER JOIN
u ON u.Id = Iif(cteuc.AuthorIsatIonGroupId = 1, #UId, cteuc.[UId])
AND u.IsDeleted = 0
LEFT OUTER JOIN
ctel ON ctel.CId = c.Id
AND ctel.Rn = 1
AND ctel.[UId] = u.Id
LEFT OUTER JOIN
(la
INNER JOIN
qla ON qla.LeadActivityId = la.Id
AND la.IsDeleted = 0
AND la.ActivityTypeId = 4
INNER JOIN
qh ON qla.QhId = qh.Id
AND qh.IsDeleted = 0
AND qh.IsReRated = 0
LEFT OUTER JOIN
(q
INNER JOIN
p ON p.Id = q.PId
AND q.IsDeleted = 0
AND p.IsDeleted = 0
) ON q.QhId = qh.Id) ON la.[UId] = u.Id
AND la.LId = ctel.LId
AND
(
#p = ''
OR
(
#p LIKE CONVERT(varchar(4), p.Id)
OR #p LIKE '%,' + CONVERT(varchar(4), p.Id) + ',%'
OR #p LIKE CONVERT(varchar(4), p.Id) + ',%'
OR #p LIKE '%,' + CONVERT(varchar(4), p.Id)
)
)
LEFT OUTER JOIN
(
SELECT
qi1.QId,
SUM(Iif(qi1.Calculation = 0, 0, qi1.Calculation + qi1.Extra)) AS FinalCalculation
FROM qi
WHERE qi1.IsDeleted = 0
GROUP BY QId
) AS qi ON qi.QId = q.Id
WHERE
(
#p = ''
OR
(
p.Id IS NOT NULL
OR qh.Id IS NULL
)
)
SELECT * FROM #FilteredData
EDIT:
just to be clear, the above query does not run any slower than this one:
DECLARE #UId int = '817'
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
IF OBJECT_ID('tempdb..#FilteredData') IS NOT NULL DROP TABLE #FilteredData;
WITH cteuag AS
(
SELECT
uag.CId,
uag.AuthorIsatIonGroupId,
rn = ROW_NUMBER() OVER (PARTITION BY uag.[UId], uag.CId, uag.AuthorIsatIonGroupId ORDER BY uag.CId)
FROM uag
WHERE uag.[UId] = #UId
AND uag.IsDeleted = 0
),
cteuc AS
(
SELECT
uc.CId,
cteuag.AuthorIsatIonGroupId,
uc.[UId],
i.FirstName + Iif(i.MiddleName IS NOT NULL, ' ' + i.MiddleName + ' ', ' ') + i.Surname AS [AName],
rn = ROW_NUMBER() OVER (PARTITION BY uc.CId, uc.[UId] ORDER BY uc.ModifiedAt)
FROM uc
INNER JOIN cteuag ON cteuag.CId = uc.CId
AND uc.IsDeleted = 0
INNER JOIN ui ON ui.[UId] = uc.[UId]
AND ui.IsDeleted = 0
INNER JOIN i ON i.PId = ui.IndividualId
),
ctel AS
(
SELECT
la.LId,
p.CId,
la.[UId],
rn = ROW_NUMBER() OVER (PARTITION BY la.LId ORDER BY la.DateUpdated DESC)
FROM la
INNER JOIN p ON p.Id = la.PId
AND p.IsDeleted = 0
AND la.IsDeleted = 0
AND la.[UId] IS NOT NULL
INNER JOIN l ON la.LId = l.Id
AND l.IsDeleted = 0
)
SELECT
c.Id AS CId,
c.[Name] AS CName,
u.Id AS AId,
cteuc.AName AS AName,
ctel.LId AS LId,
qh.Id AS QhId,
q.Id AS QId,
q.IsTrue AS isTrue,
p.Id AS PId,
p.[Name] AS PName,
qi.FinalCalculation AS Calculation
INTO #FilteredData
FROM c
INNER JOIN cteuc ON cteuc.CId = c.Id
AND cteuc.Rn = 1
AND c.IsDeleted = 0
LEFT OUTER JOIN u ON u.Id = Iif(cteuc.AuthorIsatIonGroupId = 1, #UId, cteuc.[UId])
AND u.IsDeleted = 0
LEFT OUTER JOIN ctel ON ctel.CId = c.Id
AND ctel.Rn = 1
AND ctel.[UId] = u.Id
LEFT OUTER JOIN
(
la
INNER JOIN qla ON qla.LeadActivityId = la.Id
AND la.IsDeleted = 0
AND la.ActivityTypeId = 4
INNER JOIN qh ON qla.QhId = qh.Id
AND qh.IsDeleted = 0
AND qh.IsReRated = 0
LEFT OUTER JOIN
(
q
INNER JOIN p ON p.Id = q.PId
AND q.IsDeleted = 0
AND p.IsDeleted = 0
) ON q.QhId = qh.Id) ON la.[UId] = u.Id
AND la.LId = ctel.LId
LEFT OUTER JOIN
(
SELECT
qi1.QId,
SUM(Iif(qi1.Calculation = 0, 0, qi1.Calculation + qi1.Extra)) AS FinalCalculation
FROM qi
WHERE qi1.IsDeleted = 0
GROUP BY QId
) AS qi ON qi.QId = q.Id
SELECT * FROM #FilteredData
so I know it is not the comma delimited values used as filters, or the leading wild cards.
So it turns out it runs fine on another laptop, which means it was something to do with my laptop. Regardless, looking at the comments, this query could use a lot of refinement

SQL Moving SUBSTRING select into INNER JOIN

I have this query
SELECT ID,
SUBSTRING(( SELECT DISTINCT ',' + CONVERT(varchar(10), CC.CompanyId)
FROM Company CC
INNER JOIN CompanyProducts NP2
ON CC.CompanyId = NP2.CompanyId
WHERE NP.CompanyProducts Id = NP2.PrimaryCompanyProducts Id
AND NP2.CompanyProducts Id <> NP2.CompanyProducts Id
FOR XML PATH('')),2,200000) AS CompanyIdList
FROM CompanyProducts NP
I would like to add the SELECT into an INNER JOIN which I will add to my select to check if the return is null or zero
it will be something like this
SELECT ID,
SUBSTRING(( SELECT DISTINCT ',' + CONVERT(varchar(10), CC.CompanyId)
FROM Company CC
INNER JOIN CompanyProducts NP2
ON CC.CompanyId = NP2.CompanyId
WHERE NP.CompanyProducts Id = NP2.PrimaryCompanyProducts Id
AND NP2.CompanyProducts Id <> NP2.CompanyProducts Id
FOR XML PATH('')),2,200000) AS CompanyIdList,
CompanyIdCount --this will be null or a real value
FROM cmp.CompanyProducts NP
INNER JOIN(SELECT DISTINCT A.CompanyProductsId,
(SELECT DISTINCT ',' + CONVERT(varchar(10), CC.CompanyId)
FROM Company CC
INNER JOIN CompanyProducts NP2
ON CC.CompanyId = NP2.CompanyId
WHERE NP.CompanyProducts Id = NP2.PrimaryCompanyProducts Id
AND NP2.CompanyProducts Id <> NP2.CompanyProducts Id ) AS CompanyIdCount
FROM cmp.CompanyProducts A
)E ON NP.CompanyNotificationId = E.CompanyNotificationId
How can I get the inner JOIN to incident null for no records or 1 record or more? THanks

Trying to join two sql statement

I would like to join Query 1 and Query 2 on TripId.
Query 1
SELECT tblTrips.TripId,tblVehicles.VehicleNo
FROM tblTrips INNER JOIN tblVehicles ON tblTrips.VehicleId = tblVehicles.VehicleId
Query 2
;with T1 as (
SELECT tblTrips.TripId, tblTripDeductions.Amount, CONVERT(VARCHAR(400),tblDeductionTypes.DeductionType+' - '+tblTripDeductions.Description+' - '+ CONVERT(VARCHAR(24),tblTripDeductions.Amount)) as DeductionFor
FROM tblTrips INNER JOIN
tblTripDeductions ON tblTrips.TripId = tblTripDeductions.TripId INNER JOIN
tblDeductionTypes ON tblTripDeductions.DeductionId = tblDeductionTypes.DeductionId
)select **T1.TripId**, SUM(T1.Amount) as Amount, stuff((select '#',' ' + CONVERT(varchar(1000),T2.DeductionFor) from T1 AS T2 where T1.TripId = T2.TripId for xml path('')),1,1,'') [Description] from T1
Group by TripId
First query's output is list of TripId and VehicleNo.
Second query's output is list of TripId, Amount and description.
And my desire output is TripId, VehicleNo, amount and description.
The Syntax for WITH (Common Table Expressions) allows you to create multiple CTE's.
Using that you can turn your final part of Query2 in to a CTE (Which I'll name Query2) and your query for Query1 can also be made in to a CTE (which I'll name Query1).
Then, the final SELECT statement can simply join those two CTE's together.
;
WITH
T1 as (
SELECT tblTrips.TripId, tblTripDeductions.Amount, CONVERT(VARCHAR(400),tblDeductionTypes.DeductionType+' - '+tblTripDeductions.Description+' - '+ CONVERT(VARCHAR(24),tblTripDeductions.Amount)) as DeductionFor
FROM tblTrips INNER JOIN
tblTripDeductions ON tblTrips.TripId = tblTripDeductions.TripId INNER JOIN
tblDeductionTypes ON tblTripDeductions.DeductionId = tblDeductionTypes.DeductionId
)
,
Query2 AS (
select **T1.TripId**, SUM(T1.Amount) as Amount, stuff((select '#',' ' + CONVERT(varchar(1000),T2.DeductionFor) from T1 AS T2 where T1.TripId = T2.TripId for xml path('')),1,1,'') [Description] from T1
Group by TripId
)
,
Query1 AS (
<Your Code For Query1>
)
SELECT
*
FROM
Query1
INNER JOIN
Query2
ON Query1.TripID = Query2.TripID
I haven't don't anything to check your queries, as the layout that you have used isn't very readable.
Just merge the queries using CTE (didn't change/review your code, just formatted it for the sake of readability - input was pretty horrible to read)
;WITH T1 AS (
SELECT tblTrips.TripId
, tblTrips.DestinationDistrictId
, tblTrips.VehicleId
, tblTrips.No
, tblVehicles.VehicleNo
, tblTrips.CoachNo
, CONVERT(VARCHAR(24), tblTrips.GoDate, 105) AS GoDate
, tblTrips.GoTime
, CASE WHEN tblTrips.IsCome=1
THEN CONVERT(VARCHAR(24), tblTrips.ComeDate, 105)
ELSE '-'
END AS ComeDate
, CASE WHEN tblTrips.IsCome=1
THEN tblTrips.ComeTime
ELSE '-'
END AS ComeTime
, CASE WHEN tblTrips.IsCome=1
THEN (SD.DistrictName + ' - ' + DD.DistrictName + ' - ' + SD.DistrictName)
ELSE (SD.DistrictName + ' - ' + DD.DistrictName)
END AS Destination
, tblSupervisors.Name AS Supervisor
, tblDrivers.Name AS Driver
, tblTrips.AdvanceAmount
, tblTrips.AdvanceDescription
FROM tblTrips
INNER JOIN tblSupervisors ON tblTrips.SuperVisorId = tblSupervisors.SupervisorId
INNER JOIN tblDrivers ON tblTrips.DriverId = tblDrivers.DriverId
INNER JOIN tblDistricts SD ON tblTrips.StartDistrictId = SD.DistrictId
INNER JOIN tblDistricts DD ON tblTrips.DestinationDistrictId = DD.DistrictId
INNER JOIN tblVehicles ON tblTrips.VehicleId = tblVehicles.VehicleId
)
, Q1 AS (
SELECT T1.TripId
, SUM(T1.Amount) AS Amount
, STUFF((
SELECT '#', ' ' + CONVERT(VARCHAR(MAX), T2.DeductionFor)
FROM T1 AS T2
WHERE T1.TripId = T2.TripId FOR XML PATH(''))
,1,1,'') AS [Description]
FROM T1
GROUP BY TripId
)
, Q2 AS (
SELECT tblTrips.TripId
, tblTripDeductions.Amount
, CONVERT(VARCHAR(400), tblDeductionTypes.DeductionType + ' - ' + tblTripDeductions.Description + ' - ' + CONVERT(VARCHAR(24), tblTripDeductions.Amount)) AS DeductionFor
FROM tblTrips
INNER JOIN tblTripDeductions ON tblTrips.TripId = tblTripDeductions.TripId
INNER JOIN tblDeductionTypes ON tblTripDeductions.DeductionId = tblDeductionTypes.DeductionId
)
SELECT *
FROM Q1
INNER JOIN Q2 ON Q1.TripId = Q2.TripId

Single Line separated records in SQL SERVER Query result

I had a query that returned multiple rows from a table. Then I converted that query to this one:
;with mycte as
(select s.FirstName + ' ' + s.LastName as Name from ClientStaff cs
left outer join Staff s on s.Id = cs.StaffId
left outer join GeneralStatus gs on gs.Id = s.StatusId
where cs.ClientId = #clientId and gs.Name = 'Active')
select #staff = (select distinct staff = REPLACE(REPLACE(REPLACE((select Name AS [data()] FROM mycte a
order by a.Name for xml path),'</row><row>',', '),'</row>',''),'<row>','') from mycte b)
It returns those rows in a single comma-separated row.
Now I don't want comma-separated values, instead I want single-line-separated values.
Can anyone tell me if it is possible or not?
Thanks in advance.
declare #staff varchar(max)
;with mycte as
(
select distinct s.FirstName + ' ' + s.LastName as Name
from ClientStaff cs
left outer join Staff s on
s.Id = cs.StaffId
left outer join GeneralStatus gs on
gs.Id = s.StatusId
where cs.ClientId = #clientId and gs.Name = 'Active'
)
select #staff = isnull(#staff + char(13), '') + Name
from mycte b
print #staff

How can I use Sql to Order By This Statement?

How can I order the list 'widgets_spec by number of widgets?
select distinct
m.p_c_id
,(select distinct '<li>' +convert(varchar,widgets) + '<br> '
from dbo.spec_master m2
where m.p_c_id = m2.p_c_id and widgets is not null
for xml path(''), type).value('.[1]', 'nvarchar(max)'
) as widgets_spec
from dbo.spec_master m
inner join dbo.ProductVaration pv on pv.p_c_id = m.p_c_id
inner join dbo.Varation v on v.varation_id = pv.varation_type_id
where v.varation_id = 4
group by m.p_c_id
Right now output looks like:
<li>10<br> <li>12<br> <li>15<br> <li>8<br>
When I want it to look like:
<li>8<br> <li>10<br> <li>12<br> <li>15<br>
Thanks for your help.
EDIT: I'm trying to order the internal select statement that concatenates the values.
You do not need both Distinct and Group By. You should use one or the other. In this case, I believe you have to use Group By for it to work.
Select m.p_c_id
, (
Select '<li>' + Cast( m2.num_of_lights As varchar(10)) + '<br /> '
From dbo.spec_master As m2
Where m.p_c_id = m2.p_c_id
And m2.num_of_lights Is Not Null
Group By m2.num_of_lights
Order By m2.num_of_lights
For Xml Path(''), type).value('.[1]', 'nvarchar(max)'
) As numLights_spec
From dbo.spec_master As m
Inner Join dbo.ProductVaration As pv
On pv.p_c_id = m.p_c_id
Inner Join dbo.Varation As v
On v.varation_id = pv.varation_type_id
Where v.varation_id = 4
Group by m.p_c_id
select distinct
m.p_c_id
,(select distinct '<li>' +convert(varchar,num_of_lights) + '<br> '
from dbo.spec_master m2
where m.p_c_id = m2.p_c_id and num_of_lights is not null
ORDER BY convert(varchar,num_of_lights)
) as numLights_spec
from dbo.spec_master m
inner join dbo.ProductVaration pv on pv.p_c_id = m.p_c_id
inner join dbo.Varation v on v.varation_id = pv.varation_type_id
where v.varation_id = 4
group by m.p_c_id
) As SubA
Some of the other answers here won't work, since ordering by the now-varchar num_of_lights will put '8' after '15' as is happening now. You want to order the numLights numerically, which isn't going to happen with those html tags around them. You can add a subselect to your subselect so that you order them, then select them with the tags around them. Example (not tested):
SELECT * FROM (
select distinct
m.p_c_id
,(select distinct '<li>' +convert(varchar,num_of_lights) + '<br> '
from (select distinct p_c_id, num_of_lights from dbo.spec_master order by num_of_lights) m2
where m.p_c_id = m2.p_c_id and num_of_lights is not null
for xml path(''), type).value('.[1]', 'nvarchar(max)'
) as numLights_spec
from dbo.spec_master m
inner join dbo.ProductVaration pv on pv.p_c_id = m.p_c_id
inner join dbo.Varation v on v.varation_id = pv.varation_type_id
where v.varation_id = 4
group by m.p_c_id
Personally, I'd just add the html tags in whatever back-end code is getting the result of the query.