Add ORDER BY statement to SELECT statement - sql-server

I have the following SELECT statement and I need to add ORDER BY [UserName].
SELECT *
FROM [UserInfo]
WHERE ([AWSAccountID] = CASE WHEN #AWSAccountID = -1 THEN [AWSAccountID]
ELSE #AWSAccountID END)
I'm having some trouble figuring out where the ORDER BY needs to go, assuming it can be added at all.

Unless I am missing something you just add your ORDER BY to the end of the query:
SELECT *
FROM [UserInfo]
WHERE ([AWSAccountID] = CASE WHEN #AWSAccountID = -1 THEN [AWSAccountID]
ELSE #AWSAccountID END)
ORDER BY [UserName]

Related

Case Statement for order by clause with multiple columns sort

I Write the following SQL query to get data order by some condition,
SELECT #NullCount = COUNT(1)
FROM #ServicesForBranch where SortValue IS NULL;
SELECT #ServiceCount = COUNT(1)
FROM Service;
SELECT * FROM #tmp t
WHERE t.IsActive = 1
ORDER BY
CASE WHEN #NullCount = #ServiceCount THEN t.SortValue ELSE t.BranchServiceSortValue,t.Name END
But error is showing in this line t.BranchServiceSortValue,t.Name as
incorrect syntax near ','
What I wrote wrong here?
Try this :
SELECT #NullCount = COUNT(1)
FROM #ServicesForBranch
where SortValue IS NULL;
SELECT #ServiceCount = COUNT(1)
FROM Service;
SELECT * FROM #tmp t
WHERE t.IsActive = 1
ORDER BY
(CASE WHEN #NullCount = #ServiceCount THEN t.SortValue ELSE t.BranchServiceSortValue END),t.Name
Each CASE statement returns only 1 value so you need another one:
ORDER BY
CASE WHEN #NullCount = #ServiceCount THEN t.SortValue ELSE t.BranchServiceSortValue END,
CASE WHEN #NullCount <> #ServiceCount THEN t.Name END
but if SortValue is unique or you don't mind a secondary sorting on Name then you can simplify to this:
ORDER BY
CASE WHEN #NullCount = #ServiceCount THEN t.SortValue ELSE t.BranchServiceSortValue END,
t.Name

Why these two cases are not equivalent

I have written a sql query that check is #Collegein not equals to 0, if so then get college_code according to that else go for all colleges.I have already used this technique but never tried it for multivalues .I have this condition in "where"
College_code in (CASE WHEN #Collegein != '0' THEN (SELECT items FROM dbo.Split(#Collegein, ',')) ELSE College_code END)
This works fine for #Collegein = '1' but fails for #Collegein = '1,2' , giving error subquery return more than 1 value.
While below code works fine for #Collegein = '1,2'
College_code in (select * from dbo.Split(#Collegein ,','))
What could be that possible solution for this or alternative solution. One more thing why "in" not working here
This cannot work. While IN clearly deals with multiple values, CASE can return only a single value. Therefore the subquery in your case is expected to return a single value and that's why you get the error. You have to use OR here:
#Collegein = '0'
OR
(
#Collegein != '0'
AND College_code IN(SELECT items FROM dbo.Split(#Collegein, ','))
)
Try this:
#Collegein = '0'
OR
EXISTS(SELECT items FROM dbo.Split(#Collegein, ',') WHERE Items = College_code)
Addition(based on Thomas's answer):
#Collegein = '0'
OR
College_code IN(SELECT items FROM dbo.Split(#Collegein, ','))

How subtract two aliases which are result of two cases

I'm struggling trying to subtract to results of a case within a SQL query. Do you guys can help me out?
Here is a "simplified" version of the query.
SELECT dbo.tbla.cola, dbo.tblb.colb, dbo.tblb.colc,
CASE WHEN
(SELECT TOP 1 dstStart
FROM tblDst
WHERE tblcd.Key = dbo.tblDst.Key) >= DTimeU AND
(SELECT TOP 1 dstEnd
FROM tblDst
WHERE tblcd.Key = dbo.tblDst.Key) <= DTimeU
THEN tblcd.ApUtc + 1 ELSE tblcd.ApUtc END AS DepDST, CASE WHEN
(SELECT TOP 1 dstStart
FROM tblDst
WHERE tblca.Key = dbo.tblDst.Key) >= ATimeU AND
(SELECT TOP 1 dstEnd
FROM tblDst
WHERE tblca.Key = dbo.tblDst.Key) <= ATimeU THEN tblca.ApUtc + 1 ELSE tblca.ApUtc END AS ArrDST
FROM ...
WHERE ...
How could I perform (ArrDST-DepDST) As DiffDST ?
Regards,
Dave
Simply wrap the query with another select :
SELECT t.*, t.ArrDST - t.DepDST as DiffDST
FROM (YOUR QUERY HERE) t
Then all the calculated columns will be available for use.

Second Order By overrides first in SQL Server

In the following code the purchase_price overrides the case order by statement.
SELECT
i.products_mpn, i.active,
i.distributor_code, i.sales_price
FROM
#duplicates d
LEFT JOIN
import i ON i.products_mpn = d.products_mpn
AND i.distributor_code = (SELECT TOP 1 distributor_code
FROM dbo.kting_ICECAT_import
WHERE products_mpn = d.products_mpn
ORDER BY
(SELECT
CASE
WHEN (i.distributor_code = 'x' or i.distributor_code = 'y') AND CAST(stock as int) > 0
THEN 2
WHEN CAST(stock as int) > 0
THEN 1
ELSE 0
END) DESC,
CAST(purchase_price AS decimal(28,12)))
Is there any way to get it to work with ordering by the case statement and then the purchase_price?
If you want the ordering of the CASE statement to be applied first followed by the ordering of the purchase_price, then your ORDER BY already has the terms in the right place. I don't know what SELECT is doing in your CASE expression, or even if your current query runs. Something like this may be what you had in mind:
ORDER BY CASE WHEN (i.distributor_code = 'x' or i.distributor_code = 'y') AND
CAST(stock as int) > 0 THEN 2
WHEN CAST(stock as int) > 0 THEN 1
ELSE 0
END DESC,
CAST(purchase_price AS DECIMAL(28,12))
The problem was in the ORDER BY SELECT. I had used columns from the left join "i.distributor_code" should just have been distributor_code

SQL Server Remove unwanted rows from a CASE statement

I do a SELECT with a CASE statement with this following:
SELECT DISTINCT
n.NiveauId, n.Description,
CASE WHEN n.NiveauId NOT IN (SELECT ccs.idNiveau WHERE ccs.centreCout = 60001) THEN 0 ELSE 1 END AS attribue
FROM pa.dbo.Niveau n
JOIN BDC.dbo.CentreCoutSecteur ccs ON n.NiveauId = ccs.idNiveau
Explication :
In case "NiveauId" is not present in the other table, the value of "attribue" is 0. Else, if it's present, the value is 1.
This works, but every rows that contains a 1 also shows the same row with a 0.
Exemple:
How would I change the SELECT query to remove the unwanted duplicate rows that contain 0?
Thanks in advance!
Try wrapping your select in a max (if you only want the rows with the highest value for attribue.
SELECT b.NiveauID, b.Description, MAX(b.attribue)
FROM
(SELECT DISTINCT
n.NiveauId, n.Description,
CASE WHEN n.NiveauId NOT IN (SELECT ccs.idNiveau WHERE ccs.centreCout = 60001) THEN 0 ELSE 1 END AS attribue
FROM pa.dbo.Niveau n
JOIN BDC.dbo.CentreCoutSecteur ccs ON n.NiveauId = ccs.idNiveau) b
Group By b.NiveauID, b.Description

Resources