Trying to Use ORDER BY on a LEFT JOIN Query - sql-server

I am trying to use a left join and concat 2 column names so that they display together in a dropdown list. This is my query so far.
SELECT DISTINCT CONCAT(CAST(Index.MR_ID AS INT),' - ', Master.MR_Name) AS MR_ID
FROM Index
LEFT JOIN Master
ON Master.MR_ID=Index.MR_ID
I want to order it by the MR_ID in the Index table but whenever I try to add an ORDER BY to the query, it will not work for me. Can someone help me out here?

WITH cte AS (
SELECT DISTINCT CONCAT(CAST(Index.MR_ID AS INT),' - ', Master.MR_Name) AS MR_ID
FROM [Index]
LEFT JOIN Master
ON Master.MR_ID=Index.MR_ID
)
SELECT *
FROM
cte
ORDER BY
MR_ID;
The above is if you want to order by the final column you got.
If you want to order by the MR_ID in the Index or Master table, it is not possible because you are using the DISTINCT operator, which means it is undetermined by the final query. In that case, you will need the below
WITH cte AS (
SELECT DISTINCT CONCAT(CAST(Index.MR_ID AS INT),' - ', Master.MR_Name) AS MR_ID
, Index.MR_ID AS sort_column
FROM [Index]
LEFT JOIN Master
ON Master.MR_ID=Index.MR_ID
)
SELECT MR_ID
FROM
cte
ORDER BY
sort_column;

Mister Positive beat me to it. I'd also prepare for nulls since you are using a left join.
select distinct concat(cast(index.mr_id as int),' - ', isnull(master.mr_name,'') as mr_id
from sindex
left join master on master.mr_id=index.mr_id
order by concat(cast(index.mr_id as int),' - ', isnull(master.mr_name,'')

I think your after this
SELECT DISTINCT CONCAT(CAST(Index.MR_ID AS INT),' - ', IsNull(Master.MR_Name, '')) AS MR_ID
FROM SIndex
LEFT JOIN Master ON Master.MR_ID=SIndex.MR_ID
Order by CONCAT(CAST(Index.MR_ID AS INT),' - ', IsNull(Master.MR_Name, ''))

Related

SQL Server 2008 - create columns from multi row data

I have the following code:
IF (OBJECT_ID('tempdb..#Data') IS NOT NULL)
BEGIN
DROP TABLE #Data
END
SELECT
t.Name, x.Time, x.Date, x.Total,
xo.DrvCommTotal, x.Name2, x.Street, x.Zip,
r.Route1
INTO
#Data
FROM
table1 xo WITH(NOLOCK)
LEFT JOIN
Table2 t WITH(NOLOCK) ON t.ID = x.ID
LEFT JOIN
Route1 r ON r.RouteID = x.RouteID
WHERE
x.Client = 1
AND x.Date = '9/13/2018'
GROUP BY
t.Name, x.Time, x.Date, x.Total, xo.DrvCommTotal, x.Name2,
x.Street, x.Zip, r.Route1
ORDER BY
Route1
SELECT DISTINCT
F.*, F2.NumOrders
FROM
#Data F
LEFT JOIN
(SELECT
Route1, COUNT(*) NumOrders
FROM
#Data
GROUP BY
Route1) F2 ON F2.Route1 = F.Route1
LEFT OUTER JOIN
(SELECT
Street + ',' + Zip Stops, Time, RouteN1
FROM
#Data
GROUP BY
RouteNo1, street, Zip) F3 ON F3.Route1 = F.Route1
WHERE
F.Route1 IS NOT NULL
ORDER BY
F.Route1
and it provides me with a list of routes and stops. The column NumOrders lets me know how many orders are on each route. I need the stops to become individual columns I will label Stop1, Stop2, etc. so that each route is only one row and all the information is contained on the row for one route.
I'm currently using the temp table because the data is so large. I can play with my SELECT statement without having to re-run the entire code.
How do I move the stops for each route into columns?
Hum.. Not quite sure I understand the question but it sounds that you want to pivot the data so that the routes break into columns. If so, I would use a sql Pivot. Here is an example from the documentation:
USE AdventureWorks2014;
GO
SELECT VendorID, [250] AS Emp1, [251] AS Emp2, [256] AS Emp3, [257] AS Emp4, [260] AS Emp5
FROM
(SELECT PurchaseOrderID, EmployeeID, VendorID
FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( [250], [251], [256], [257], [260] )
) AS pvt
ORDER BY pvt.VendorID;
Also, here is the link to how to use pivot: https://learn.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-2017
Since you already have all the data in your temp table, you could pivot that on the way out.

Distinct columns after "ORDER BY" in SQL server 2014

I want to distinct columns after ORDER BY points.pPoint.
this is points table diagram:
I want something as following image on the right side but getting result as the left side:
and this is my code:
SELECT TOP(6) MedicalExpertise.meid
FROM physician INNER JOIN
MedicalExpertise ON physician.meid = MedicalExpertise.meid INNER JOIN
points ON physician.phId = points.phID
ORDER BY points.pPoint DESC
Perhaps something like this?
SELECT DISTINCT meid
FROM ( SELECT TOP ( 6 ) MedicalExpertise.meid
FROM physician
INNER JOIN MedicalExpertise ON physician.meid = MedicalExpertise.meid
INNER JOIN points ON physician.phId = points.phID
ORDER BY points.pPoint DESC ) d
ORDER BY 1 DESC;
Simply use distinct keyword,
Ex:
SELECT DISTINCT column1, column2, ...
FROM table_name;
Can you edit the original question what you really want? Does it have to be grouped by any column before getting distinct? Please update the question.

Count of rows from a joined table SQL Server

Is it possible to make a count of rows (I am using a view) with a resultset of a subquery?
Assuming I have
Table1
t1id
Table2
id, t1id_Parent, t1id_Child
Table3
t1id
I query for
select
t1.t1id as id,
stuff((select ', ' + CAST(CASE WHEN t2.t1id_Child is not null THEN t2.t1id_Child ELSE '0' END AS varchar) from Table1 t where t.t1id_Parent = t1.t1id for xml path('')),1,2,'') as ids
FROM
Table1 as t1
LEFT OUTER JOIN
Table1 AS t2 ON t1.t1id = t2.t1id_Parent
So I have the needed ids combined into a string that looks like this '1,2,5,9' in the column named "ids" that is working correctly however what I need to do now is have this query
select
t1.t1id as id,
stuff((select ', ' + CAST(CASE WHEN t2.t1id_Child is not null THEN t2.t1id_Child ELSE '0' END AS varchar) from Table1 t where t.t1id_Parent = t1.t1id for xml path('')),1,2,'') as ids
FROM
Table1 as t1
LEFT OUTER JOIN
Table2 AS t2 ON t2.t1id_Parent = t1.t1id
LEFT OUTER JOIN
(select count(t1id) as rows_count, t1id
from Table3
group by t1id) as docs ON docs.t1id in (ids)
to retrieve the row count from the 3rd table using the temporary column however I am getting an error of Invalid column name 'ids'
Is this possible or do I need to first run that query and then go back and run a new one for the count of the third table?
The result I need is
Table1.t1id, count(Table3.t1id)
Table3.t1id comes from Table1.t1id and all Table2.t1id_Child relation through Table1.t1id = Table2.t1id_Parent
I guess not possible, but got it partially working with CTE, I am now getting the list of say I have this '15673,15690,90987,45058' I can then do the query for the third column but getting the error
WITH items AS
(
select
a.ItemID,
stuff(
(select ',' +
CAST(
CASE WHEN b.[ChildItemID] is not null
THEN b.[ChildItemID] ELSE 0 END AS varchar)
from Table2 t2
where t2.[ParentItemID] = a.ItemID
for xml path('')
),1,2,'')
select
items.*,
docs.docs_count
from items
LEFT OUTER JOIN (
select count([DocID]) as docs_count from Table3
group by DocID
) as docs ON docs.ItemID in (items.ItemID)
Conversion failed when converting the nvarchar value '15673,' to data type int.
Note that the issue is not concatenating, I am getting the result expected there, a comma separated list of values, the issue comes when I try to use the comma separated values in "as docs ON docs.ItemID in (items.ItemIDs)"

How can I remove this case statement?

select id, shelfno, sectionno,
iif(tableA.shelfno = tableB.promono, itemdesc + ' Best Sale Right Now!', itemdesc),
salesprice
from tableA
left join tableB on tableA.shelfno = tableB.promono
The query works as it is, however, I wonder if there's a better way of doing/writing this. I was thinking of using a outer apply, but it's not looking that would work.
EDIT: To be clearer, I'm trying to remove the IIF (same thing as CASE) from the SELECT statement.
No CASE, no IIF, as requested...
select id, shelfno, sectionno,
COALESCE(promodesc, itemdesc),
salesprice
from tableA A
OUTER APPLY (
SELECT
itemdesc + ' Best Sale Right Now!' AS promodesc
FROM tableA
INNER JOIN tableB on tableA.shelfno = tableB.promono
WHERE id = A.id
) B
You could use CASE WHEN.
SELECT id
,shelfno
,sectionno
,itemdesc + CASE WHEN tableA.shelfno = tableB.promono
THEN ' Best Sale Right Now!'
ELSE '' END
,salesprice
FROM tableA
LEFT JOIN tableB
ON tableA.shelfno = tableB.promono
Is this what you're looking for?
case
tableB.promono is null then itemdesc
else itemdesc + ' Best Sale Right Now!'
end
This assumes that the left join is only being used in your if and no other columns are being used from tableB (which would be clearer if you aliased them all):-
SELECT id, shelfno, sectionno, itemdesc + CASE WHEN exists(
select *
from tableB
where tableB.promono = tableA.shelfno) THEN ' Best Sale Right Now!'
ELSE '' END as itemdesc,
salesprice
FROM tableA
or in Sql Server 2012:-
SELECT id, shelfno, sectionno, itemdesc + iif(exists(
select *
from tableB
where tableB.promono = tableA.shelfno),' Best Sale Right Now!','') as itemdesc,
salesprice
FROM tableA

IN NOT IN SQL Server 2005

How can I see what is not in the table... I know I know...can only see what is there but come on!!!
So!!
select * from ORDER where State IN ('MA','PA','GA','NC')
So I will get MA and PA but I want to see GA and NC....
NOT IN will return NY,NJ,CT ect.... I just want to see what is in the ( )
It looks like you are missing a single quote ' in front of GA.
My understanding of the question is: For a given list of states, which ones do not exist in the Order table?
This will show you what states out of the four listed below have no corresponding records in the Order table:
select distinct s.State
from
(
select 'MA' as State
union all
select 'PA'
union all
select 'GA'
union all
select 'NC'
) s
left outer join [Order] o on s.State = o.State
where o.State is null
I'm going to try to read between the lines a little here:
;with cteStates as (
select 'MA' as state
union all
select 'PA'
union all
select 'GA'
union all
select 'NC'
)
select s.state, count(o.state) as OrderCount
from cteStates s
left join [order] o
on s.state = o.state
group by s.state
Are you just trying to find out which states there are except for those four? If so:
SELECT DISTINCT State FROM dbo.ORDER WHERE State NOT IN ('MA', 'PA', 'GA', 'NC')

Resources