How can I use Sql to Order By This Statement? - sql

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.

Related

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

Return SQL Sub Query with a variable inside Select

My Application is a cash register. The following query takes a TransactionID and returns one or more rows of items sold in this single transaction i.e. for TransactionID = 28715:
DECLARE #SalesItems varchar(250);
DECLARE #TransactionID int;
SET #TransactionID = 28715;
Select #SalesItems = coalesce(#SalesItems + ', ', '') + CAST(TransactionsPosLines.Description as varchar(250))
From
TransactionsPosLines
where TransactionsPosLines.TransactionId = #TransactionID
select #SalesItems
and returns:
"Widget A, Widget B, Widget C" as a single string.
I also have an end of day transaction report which I want to append the string (Widget A etc...) onto the end of the transaction report.
Select
Transactions.TransactionId,
Transactions.TransactionDate,
Transactions.MoneyIn,
Transactions.MoneyOut,
Transactions.Description,
PaymentMethods.PaymentMethodName,
Transactions.TransactionRef,
Membership.Username,
Tills.Description As 'Till Name',
Transactions.Reason,
-- FOR THIS LAST COLUMN HERE I WANT TO SHOW THE OUTPUT OF THE QUERY ABOVE
====> SalesItems
From
Transactions Left Outer Join
Tills
On Transactions.TillId = Tills.TillId Inner Join
PaymentMethods
On Transactions.PaymentMethodId = PaymentMethods.PaymentMethodsID Inner Join
Membership
On Transactions.UserId = Membership.UserId Inner Join
Where
Transactions.TransactionDate >= #DateStart And
Transactions.TransactionDate <= #DateEnd
So when I run this report I get something like this:
TransactionId TransactionDate MoneyIn MoneyOut Description PaymentMethodName TransactionRef Username Till Name Reason SalesItems
28715 31/08/2016 09:07 119.99 0 Sale - Card Card 24881 Chantal Till1 Null Widget A, Widget B, Widget C
CROSS APPLY WITH FOR XML CONCATENATION METHOD:
Select
t.TransactionId,
t.TransactionDate,
t.MoneyIn,
t.MoneyOut,
t.Description,
p.PaymentMethodName,
t.TransactionRef,
m.Username,
tl.Description As 'Till Name',
t.Reason,
c.SalesItems
From
Transactions t
LEFT JOIN Tills tl
ON t.TillId = tl.TillId
INNER JOIN PaymentMethods p
ON t.PaymentMethodId = p.PaymentMethodID
INNER JOIN Membership m
On t.UserId = m.UserId
CROSS APPLY
(SELECT STUFF(
(SELECT ',' + CAST(tp.Description AS VARCHAR(100))
FROM
TransactionPostLines tp
WHERE t.TransactionId = tp.TransactionId
FOR XML PATH(''))
,1,1,'') as SalesItems) c
Where
t.TransactionDate >= #DateStart
AND t.TransactionDate <= #DateEnd
AS Sub Select in column Definition:
Select
t.TransactionId,
t.TransactionDate,
t.MoneyIn,
t.MoneyOut,
t.Description,
p.PaymentMethodName,
t.TransactionRef,
m.Username,
tl.Description As 'Till Name',
t.Reason,
STUFF(
(SELECT ',' + CAST(tp.Description AS VARCHAR(100))
FROM
TransactionPostLines tp
WHERE t.TransactionId = tp.TransactionId
FOR XML PATH(''))
,1,1,'') as SalesItems
From
Transactions t
LEFT JOIN Tills tl
ON t.TillId = tl.TillId
INNER JOIN PaymentMethods p
ON t.PaymentMethodId = p.PaymentMethodID
INNER JOIN Membership m
On t.UserId = m.UserId
Where
t.TransactionDate >= #DateStart
AND t.TransactionDate <= #DateEnd
Note using table aliases makes the code easier to read and to write!
I have used cross apply in order to apply result to inner query to each row of your main query. Check whether this helps you:
Select
Transactions.TransactionId,
Transactions.TransactionDate,
Transactions.MoneyIn,
Transactions.MoneyOut,
Transactions.Description,
PaymentMethods.PaymentMethodName,
Transactions.TransactionRef,
Membership.Username,
Tills.Description As 'Till Name',
Transactions.Reason,
-- HERE >>
--SalesItems =
dt.salesItems
From
Transactions Left Outer Join
Tills
On Transactions.TillId = Tills.TillId Inner Join
PaymentMethods
On Transactions.PaymentMethodId = PaymentMethods.PaymentMethodsID Inner Join
Membership
On Transactions.UserId = Membership.UserId
cross apply (
select distinct stuff((
Select ',' + CAST(TransactionsPosLines.Description as varchar(250))
From
TransactionsPosLines
where TransactionsPosLines.TransactionId = Transactions.TransactionId
FOR XML PATH('')),1,1,'') as salesItems
) as dt
-- TransactionsPosLines
-- On TransactionsPosLines.TransactionId = Transactions.TransactionId
Where
Transactions.TransactionDate >= #DateStart And
Transactions.TransactionDate <= #DateEnd

Issue with Order By with FOR XML in T-sql (The ORDER BY clause is invalid in views, inline functions, derived tables)

select a.Hall, a.Title,
STUFF((SELECT ', ' + '[' + CONVERT(varchar(2),DATEPART(Hour, b.StartFilm))
+ ':' + CONVERT(varchar(2),DATEPART(Minute, b.StartFilm))
+ ' ' + CONVERT(varchar(2),DATEPART(Hour, b.EndTime))
+ ':' + CONVERT(varchar(2),DATEPART(Minute, b.EndTime))
+ ']'
FROM (select c.Name as Hall, b.Title,
Convert(time,a.StartFilmTime) as StartFilm,
Convert(time,a.EndFilmTime) as EndTime
from FilmSchedule a
left join Film b on a.FilmId = b.Id
left join Room c on a.RoomId = c.Id
where a.ApproveStatus = 1 and a.Status = 1
and CONVERT(date, a.StartFilmTime) = '05-06-2015'
) b
Where a.Hall = b.Hall and a.Title = b.Title
FOR XML PATH('')),1,1,'') As ShowTime
from (select c.Name as Hall, b.Title,
Convert(time,a.StartFilmTime) as StartFilm,
Convert(time,a.EndFilmTime) as EndTime
from FilmSchedule a
left join Film b on a.FilmId = b.Id
left join Room c on a.RoomId = c.Id
where a.ApproveStatus = 1 and a.Status = 1
and CONVERT(date, a.StartFilmTime) = '05-06-2015'
Order by a.StartFilmTime
) a
group by a.Hall, a.Title
I get the error:
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.
Help please! (I have used FOR XML?)
Although your query does use FOR XML (for the GROUP_CONCAT workaround), you are applying the order by outside of the derived table that uses FOR XML, hence the error.
Given that you aren't including start date directly in the final select (although you are composing it as part of the STUFF ShowTime column), you also can't ORDER BY StartFilm in the final GROUP BY either, as the column would otherwise need to be included in the GROUP BY or as an aggregated column.
What you can do is move the ORDER BY into the STUFF and then order by the derived column ShowTime (since your query only runs for one given day, and StartFilmTime is the first part of the STUFFED composed column).
At the same time, I would DRY up the repetition on the derived table with a CTE:
WITH cteFiltered AS
(select c.Name as Hall, b.Title,
Convert(time,a.StartFilmTime) as StartFilm,
Convert(time,a.EndFilmTime) as EndTime
from FilmSchedule a
left join Film b on a.FilmId = b.Id
left join Room c on a.RoomId = c.Id
where a.ApproveStatus = 1 and a.Status = 1
and CONVERT(date, a.StartFilmTime) = '05-06-2015'
)
select
a.Hall,
a.Title,
STUFF((SELECT ', ' + '[' + CONVERT(varchar(2),DATEPART(Hour, b.StartFilm))
+ ':' + CONVERT(varchar(2),DATEPART(Minute, b.StartFilm))
+ ' ' + CONVERT(varchar(2),DATEPART(Hour, b.EndTime))
+ ':' + CONVERT(varchar(2),DATEPART(Minute, b.EndTime))
+ ']'
FROM
cteFiltered b
Where
a.Hall = b.Hall and a.Title = b.Title
order by b.StartFilm -- ***
FOR XML PATH('')),1,1,'') As ShowTime
from
cteFiltered a
group by a.Hall, a.Title
order by ShowTime; -- *** Hour is first (assuming 24H format) and only one day

Subquery in view runs slow

Hello i have an issue with my view. The Subquery causes the view to run very slowly.
SELECT dbo.Calls.CallID
,dbo.Calls.StartTime
,dbo.Calls.EndTime
,dbo.Connections.Connectionname
,dbo.Repositorys.RepositoryName
,REPLACE(dbo.Calls.Querytime ,',' ,'.') AS Querytijd
,dbo.Calls.Uur
,dbo.Calls.DayOfMonth
,REPLACE(
(
SELECT MAX(Querytime) AS MaxQueryTime
FROM dbo.Calls AS C
WHERE (
DATEPART(yyyy ,StartTime)=DATEPART(yyyy ,dbo.Calls.StartTime)
)
AND (DATEPART(M ,StartTime)=DATEPART(M,dbo.Calls.StartTime))
AND (DayOfMonth=dbo.Calls.DayOfMonth)
AND (Uur=dbo.Calls.Uur)
AND (
DATEPART(MINUTE ,dbo.Calls.StartTime)=DATEPART(Minute ,StartTime)
)
)
,','
,'.'
) AS MaxQueryTime
FROM dbo.Calls
INNER JOIN dbo.Connections
ON dbo.Calls.ConnectionID = dbo.Connections.ConnectionID
LEFT OUTER JOIN dbo.Repositorys
ON dbo.Connections.RepositoryID = dbo.Repositorys.RepositoryID
I basically want the maximum QueryTime where the year/month/day/hour/minute of the StartTime is the same.
In SQLServer2005+ you can use OVER() clause
SELECT dbo.Calls.CallID,
dbo.Calls.StartTime,
dbo.Calls.EndTime,
dbo.Connections.Connectionname,
dbo.Repositorys.RepositoryName,
REPLACE(dbo.Calls.Querytime, ',', '.') AS Querytijd,
dbo.Calls.Uur,
dbo.Calls.DayOfMonth,
REPLACE(MAX(Querytime) OVER(PARTITION BY DATEPART(yyyy ,StartTime),
DATEPART(Minute ,StartTime),
DayOfMonth, Uur), ',', '.'
) AS MaxQueryTime
FROM dbo.Calls INNER JOIN dbo.Connections
ON dbo.Calls.ConnectionID = dbo.Connections.ConnectionID
LEFT OUTER JOIN dbo.Repositorys
ON dbo.Connections.RepositoryID = dbo.Repositorys.RepositoryID
Is it Query working ?
When i look at your Query "From" keyword are used twice in single Query.
There are join of two tables only. if you want to make your result fast then filter both table first then make join so there will be less number of row in join which will optimize your result.
SELECT dbo.Calls.CallID, dbo.Calls.StartTime, dbo.Calls.EndTime,
dbo.Connections.Connectionname, dbo.Repositorys.RepositoryName,
REPLACE(dbo.Calls.Querytime, ',', '.') AS Querytijd, dbo.Calls.Uur,
dbo.Calls.DayOfMonth, REPLACE((SELECT MAX(Querytime) AS MaxQueryTime
FROM dbo.Calls AS C
WHERE (DATEPART(yyyy, StartTime) = DATEPART(yyyy, dbo.Calls.StartTime))
AND (DayOfMonth = dbo.Calls.DayOfMonth) AND (Uur = dbo.Calls.Uur) AND
(DATEPART(MINUTE, dbo.Calls.StartTime) = DATEPART(Minute, StartTime))), ',', '.') AS MaxQueryTime
FROM dbo.Calls INNER JOIN dbo.Connections ON dbo.Calls.ConnectionID = dbo.Connections.ConnectionID
LEFT OUTER JOIN dbo.Repositorys ON dbo.Connections.RepositoryID = dbo.Repositorys.RepositoryID
SELECT dbo.Calls.CallID
,dbo.Calls.StartTime
,dbo.Calls.EndTime
,dbo.Connections.Connectionname
,dbo.Repositorys.RepositoryName
,REPLACE(dbo.Calls.Querytime ,',' ,'.') AS Querytijd
,dbo.Calls.Uur
,dbo.Calls.DayOfMonth
,REPLACE( QUERYTIME,',','.') AS MaxQueryTime
FROM dbo.Calls
INNER JOIN dbo.Connections
ON dbo.Calls.ConnectionID = dbo.Connections.ConnectionID
LEFT OUTER JOIN dbo.Repositorys
ON dbo.Connections.RepositoryID = dbo.Repositorys.RepositoryID
LEFT JOIN
(
SELECT StartTime, Uur, DayOfMonth, StartTime, MAX(QUERYTIME) AS QUERYTIME
FROM dbo.Calls
GROUP BY StartTime, Uur, DayOfMonth, StartTime
) AS C
ON DATEPART(yyyy ,C.StartTime)=DATEPART(yyyy ,dbo.Calls.StartTime)
AND C.DayOfMonth=dbo.Calls.DayOfMonth
AND C.Uur=dbo.Calls.Uur
AND DATEPART(MINUTE ,dbo.Calls.StartTime)=DATEPART(Minute ,C.StartTime)
When i look at your Query .. you are calculating "MaxQueryTime" for each row. To Optimize this Query you can calculate "MaxQueryTime" once then using union Keyword you can combine to your result set. According to me "MaxQueryTime" will be same for all.
(SELECT REPLACE(MAX(Querytime),',','.') AS MaxQueryTime
FROM dbo.Calls AS C
WHERE (
DATEPART(yyyy ,StartTime)=DATEPART(yyyy ,dbo.Calls.StartTime)
)
AND (DayOfMonth=dbo.Calls.DayOfMonth)
AND (Uur=dbo.Calls.Uur)
AND (
DATEPART(MINUTE ,dbo.Calls.StartTime)=DATEPART(Minute ,StartTime)
)) union all
( SELECT dbo.Calls.CallID
,dbo.Calls.StartTime
,dbo.Calls.EndTime
,dbo.Connections.Connectionname
,dbo.Repositorys.RepositoryName
,REPLACE(dbo.Calls.Querytime ,',' ,'.') AS Querytijd
,dbo.Calls.Uur
,dbo.Calls.DayOfMonth
FROM dbo.Calls
INNER JOIN dbo.Connections
ON dbo.Calls.ConnectionID = dbo.Connections.ConnectionID
LEFT OUTER JOIN dbo.Repositorys
ON dbo.Connections.RepositoryID = dbo.Repositorys.RepositoryID )

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