I'm running the following query in SQL server and it's giving me the error:
'Results' has fewer columns than were specified in the column list.
I'm clearly listing several columns so I'm not sure what the problem is. I tried putting only Results( ContractDesc ) and it resolved the error, so I guess it thinks I'm only selecting one column inside that query. How do I solve this?
SELECT
Cl.LegalName AS ClientNames,
Results.ContractDesc AS ContractNames,
Results.ProjectNames AS ProjectNames,
Results.EmployeeNames AS EmployeeNames,
Results.TotalHours AS TotalHours,
Results.TotalCharges AS TotalCharges,
Results.BillingContacts AS BillingContacts
FROM Clients Cl
CROSS APPLY (
SELECT
( Cr.ContractDesc + ', ' ) AS ContractDesc,
( P.ProjectName + ', ' ) AS ProjectNames,
( E.FirstName + ' ' + E.LastName + ', ' ) AS EmployeeNames,
( WH.HoursWorked + ', ' ) AS TotalHours,
( WH.HoursWorked * BR.Rate ) + ', ' AS TotalCharges,
( Ca.FirstName + Ca.LastName + ', ' + Ca.AddrLine1 + ', ' ) AS BillingContacts
FROM Contracts Cr
JOIN Projects P ON( Cr.ContractID = P.ContractID )
JOIN EmployeesProjects EP ON( P.ProjectID = EP.ProjectID )
JOIN Employees E ON( EP.EmpID = E.EmpID )
JOIN WorkHours WH ON( E.EmpID = WH.EmpID )
JOIN BillingRates BR ON( E.TitleID = BR.TitleID ) AND ( E.Level = BR.Level )
JOIN ContractsContacts CC ON( Cr.ContractID = CC.ContractID )
JOIN Contacts Ca ON( CC.ContactID = Ca.ContactID )
WHERE( Cl.ClientID = Cr.ClientID )
AND ( WH.WH_Month = 4 )
AND ( WH.WH_Year = 2013 )
GROUP BY Cr.ContractID,
Cr.ContractDesc,
P.ProjectName,
E.FirstName,
E.LastName,
WH.HoursWorked,
BR.Rate,
Ca.FirstName,
Ca.LastName,
Ca.AddrLine1
FOR XML PATH( '' )
) Results ( ContractDesc, ProjectNames, EmployeeNames, TotalHours, TotalCharges, BillingContacts )
ClientNames appears to be missing from Results().
Related
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
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
I need to limit the row number to one unique row in SQL query. Here's sample data to recognize what I'm talking about:
john doe 3000 fog horn drive , ky 40444
john doe 3001 merry lane , ky 40484
I want to return the first one in the list here's my query :
Select
DISTINCT p.personID, e.citizenship,
rtrim(i.lastname + CASE WHEN i.suffix IS NULL THEN '' ELSE ' ' + i.suffix END) + ', ' + i.firstname + (CASE WHEN i.middlename IS NULL THEN '' ELSE ' ' + i.middlename END) StuName,
e.grade, i.gender, p.studentNumber, e.citizenship, e.adult, i.birthdate,
e.disability1, e.disability2, ad.city, e.displacedHomemaker, e.homeSchooled,
e.localStudentNumber, e.migrant, e.modifiedDate, e.modifiedByID,
rtrim(Staff.lastname + CASE WHEN Staff.suffix IS NULL THEN '' ELSE ' ' + Staff.suffix END) + ', ' + Staff.firstname + (CASE WHEN Staff.middlename IS NULL THEN '' ELSE ' ' + Staff.middleName END) Staffname,
Staff.personID Staffid, i.lastname, i.firstname, i.middlename, i.ssn,
ad.phone, ad.state, ad.zip, ad.addressLine1
FROM
Person p
LEFT join
Enrollment e ON e.personID = p.personID And isnull(e.noshow, 0) = 0
LEFT join
EnrollmentKY ky ON ky.enrollmentID = e.enrollmentID
LEFT join
[Identity] i ON i.identityID = p.currentIdentityID And i.personID = p.personID
INNER join
Calendar c ON c.calendarID = e.calendarID
INNER join
SchoolYear sy ON sy.endYear = c.endYear AND sy.active = 1
JOIN
staffMember Staff ON Staff.personID = e.modifiedByID
--join view_students s ON s.personID = i.personID
left join
v_MailingAddress ad ON ad.personID = i.personID And ad.relatedBy = 'household'
And ad.endDate IS NULL And isnull(ad.secondary, 0) = 0
order by
i.lastname, i.firstname, i.middlename
edit: need to only pick first row in SQL code because I have a problem with people that have multiple addresses it puts two rows for them and i only need first row of data for the person that has multiple addresses.
If the personId is distinct for each of the records and they just have a different address, then you can add a field for the row_number() and then only select the records where the row_number = 1:
select *
from
(
Select p.personID,
e.citizenship,
rtrim(i.lastname + CASE WHEN i.suffix IS NULL THEN '' ELSE ' ' + i.suffix END) + ', ' + i.firstname + (CASE WHEN i.middlename IS NULL THEN '' ELSE ' ' + i.middlename END) StuName,
e.grade,
i.gender,
p.studentNumber,
e.citizenship,
e.adult,
i.birthdate,
e.disability1,
e.disability2,
ad.city,
e.displacedHomemaker,
e.homeSchooled,
e.localStudentNumber,
e.migrant,
e.modifiedDate,
e.modifiedByID,
rtrim(Staff.lastname + CASE WHEN Staff.suffix IS NULL THEN '' ELSE ' ' + Staff.suffix END) + ', ' + Staff.firstname + (CASE WHEN Staff.middlename IS NULL THEN '' ELSE ' ' + Staff.middleName END) Staffname,
Staff.personID Staffid,
i.lastname,
i.firstname,
i.middlename,
i.ssn,
ad.phone,
ad.state,
ad.zip,
ad.addressLine1,
row_number() over(partition by p.personid order by p.personid) rn -- add this field
FROM Person p
LEFT join Enrollment e
ON e.personID = p.personID
And isnull(e.noshow,0)=0
LEFT join EnrollmentKY ky
ON ky.enrollmentID = e.enrollmentID
LEFT join [Identity] i
ON i.identityID = p.currentIdentityID
And i.personID = p.personID
INNER join Calendar c
ON c.calendarID = e.calendarID
INNER join SchoolYear sy
ON sy.endYear = c.endYear
AND sy.active = 1
JOIN staffMember Staff
ON Staff.personID = e.modifiedByID
--join view_students s ON s.personID = i.personID
left join v_MailingAddress ad
ON ad.personID = i.personID
And ad.relatedBy = 'household'
And ad.endDate IS NULL
And isnull(ad.secondary,0)=0
) x
where x.rn = 1
order by x.lastname, x.firstname, x.middlename
Try using the LIMIT to limit the no. of outputs.
Eg:
SELECT COLUMN_NAME
FROM TABLE
ORDER BY CONDITION
LIMIT NO_OF_ROWS;
Have you tried using a "GROUP BY" clause instead of the DISTINCT keyword?
Also, what about a Sub-Query? If I were writing this type of thing I'd use a sproc and create a temporary table.
Edit: Deleted original answer as question was changed and original answer is not the way to go with changed question.
Suggest GROUP BY clause per Neil Hoskins.
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 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.