SQL Query problem (2 different order by) in 1 table - sql

This is the original table:
I have 2 different query and I want to make 1 query for these:
SELECT *
FROM SAMPLE
WHERE ORDER_PRIORITY<40
ORDER BY FS_GENERATE_DATE IS NOT NULL, FS_GENERATE_DATE,ORDER_PRIORITY,CREATE_ID,CR_DATE,ORDER_QTY;
second:
SELECT *
FROM SAMPLE
WHERE ORDER_PRIORITY>=40
ORDER BY FS_GENERATE_DATE IS NOT NULL, FS_GENERATE_DATE,ORDER_PRIORITY,CREATE_ID,CR_DATE,ORDER_QTY;
I need the next result in only 1 query:
if the order_priority<40 than the order will be the first according to the order by
but if order_priority>=40 than these data will be after the lower priority (first conditional /op<40/).
Result:

You can add this to your order by clause:
case when ORDER_PRIORITY<40 then 0 else 1 end
The final query will be:
SELECT
*
FROM SAMPLE
WHERE ORDER_PRIORITY>=40
ORDER BY
case when ORDER_PRIORITY<40 then 0 else 1 end,
FS_GENERATE_DATE IS NOT NULL, FS_GENERATE_DATE,ORDER_PRIORITY,CREATE_ID,CR_DATE,ORDER_QTY;

You are clearly using a database where booleans are allowed in the ORDER BY. So, you can just use:
SELECT S.*
FROM SAMPLE S
ORDER BY (ORDER_PRIORITY < 40) DESC,
FS_GENERATE_DATE IS NOT NULL,
FS_GENERATE_DATE,
ORDER_PRIORITY,
CREATE_ID, CR_DATE, ORDER_QTY;

Related

Remove the duplicate rows based on Presence of Number of NULL values in a row

I was able to remove the duplicate rows, but I would like to remove the duplicate rows based on one more constraint. I want to keep only a row with a smaller number of NULL values.
Original Table
Ran the SQL Server Query
WITH CTE AS(
SELECT *,
RN = ROW_NUMBER()OVER(PARTITION BY Premise_ID ORDER BY Premise_ID)
FROM sde.Premise_Test
)
DELETE FROM CTE WHERE RN > 1
Result:
But I want to get this result
I have modified the SQL script as per the comment from Aaron. but the result is still the same. DB fiddle is showing NULL from IS NULL getting highlighted.
Update the ROW_NUMBER() function like this (no, there is no shorter way):
RN = ROW_NUMBER() OVER (
PARTITION BY Premise_ID
ORDER BY Premise_ID,
CASE WHEN Division IS NULL THEN 1 ELSE 0 END
+ CASE WHEN InstallationType IS NULL THEN 1 ELSE 0 END
+ CASE WHEN OtherColumn IS NULL THEN 1 ELSE 0 END
...
)

PGSQL: SORT isnt executed with rollup having only one result

I'm having this code:
SELECT "monat",
CASE
WHEN count("erstkontakt_reaktionsdauer") < 3
THEN null
ELSE round(round(count("erstkontakt_reaktionsdauer"),2) / nullif(count("erstkontakt_reaktionsdauer"),0), 4)
END,
count("erstkontakt_reaktionsdauer")
FROM "schema"."tablename"
WHERE "monat" IN ('2021-04-01')
AND "monat" IS NOT NULL
GROUP BY rollup(1 )
HAVING count(*) >= 1
ORDER BY 1 NULLS FIRST
While this worked all along, When I have more than one month in
WHERE "monat" IN ('2021-04-01')
When I have only one inside the WHERE, the ROLLUP NULL isnt coming first
Using a temporary table works
SELECT * FROM (
SELECT "monat", CASE WHEN count("erstkontakt_reaktionsdauer") < 3 THEN null ELSE round(round(count("erstkontakt_reaktionsdauer"),2) / nullif(count("erstkontakt_reaktionsdauer"),0), 4) END, count("erstkontakt_reaktionsdauer") FROM "schema"."table" WHERE "monat" IN ('2021-03-01') AND "monat" IS NOT NULL GROUP BY rollup(1 ) HAVING count(*) >= 1
) t ORDER BY 1 NULLS FIRST
The Problem is, when there is only one result of the query (Rollup isnt counted), the SORT method isnt called. Using a temporary table solves this.

Null value in order by clause

I have a weird scenario, in which I need to keep all the rows at top in which X column has NULL value else sort by Y column. Can you help me in writing query.
ORDER BY CASE WHEN X IS NULL THEN 0 ELSE 1 END, Y
You can use a CASE statement in ORDER BY:
ORDER BY
CASE WHEN X IS NULL THEN 0 ELSE 1 END ASC, Y
Here you go, this will work with any sql platform -- for a specific platform there might be a better way to do it.
SELECT * FROM
(
SELECT 1 AS orderC, *
FROM tableName
WHERE Xcolumn is null
UNION ALL
SELECT 2 AS orderC, *
FROM tableName
WHERE Xcolumn is not null
)
ORDER BY orderC ASC, columnY
Note, if you don't want orderC to be in the output, just specify all the other columns in the outer select.
Sharing what I learned before using:
ORDER BY FIELD(Xcolumn, NULL) DESC, Ycolumn DESC
SELECT * FROM TABLENAME ORDER BY X ,Y
You can use query like below:
SELECT * FROM Emp WHERE empId= 6 AND DELETED = 0
ORDER BY CASE WHEN DOB IS NULL THEN 0 ELSE 1 END
, CREATETIMESTAMP.
for more details you can see here

Adjust SQL Query to force a record to appear first?

How can the below query be adjusted to return always the member with MemberID = 'xxx' as the first row
SELECT * FROM Members
select * from Members
order by case when MemberID = XXX then 0 else 1 end
This should work and it will also allow you to order the remaining items by MemberID (Assuming xxx=12 in this example)
SELECT *
FROM Members
ORDER BY CASE WHEN MemberID=12 THEN NULL ELSE isnull(MemberID,0) END
If the memberID column can't contain nulls, you can get away with this which might perform slightly better.
SELECT *
FROM Members
ORDER BY CASE WHEN MemberID=12 THEN NULL ELSE MemberID END
SELECT
CASE WHEN MemberID = 'xxx' AS 1 ELSE 0 END CASE AS magic,
*
FROM Members
ORDER BY magic DESC
The syntax might vary depending on yr db, but I hope you get the idea.
SELECT * FROM `Members` WHERE `MemberID` = '[ID]' LIMIT 1 UNION SELECT * FROM `Members`
This should work. Tested on my database instance. Chosen ID is always first.
A more robust solution, if you have more than one record that has to be floated to the top, or if you have a specific order for multiple records, is to add a ResultsOrder column to your table, or even another table MemberOrder(memberid, resultorder). Fill resultorder with big numbers and ...
Select m.*
From Members m
Left Join MemberOrder mo on m.MemberID=mo.MemberID
Order by coalesce(mo.resultorder, 0) DESC
try this:
SELECT * FROM Members
ORDER BY IF(x.MemberId = XXX, -1, ABS(x.MemberId))

Order by Maximum condition match

Please help me to create a select query which contains 10 'where' clause and the order should be like that:
the results should be displayed in order of most keywords(where conditions) matched down to least matched.
NOTE: all 10 condition are with "OR".
Please help me to create this query.
i am using ms-sql server 2005
Like:
Select *
from employee
where empid in (1,2,4,332,434)
or empname like 'raj%'
or city = 'jodhpur'
or salary >5000
In above query all those record which matches maximum conditions should be on top and less matching condition record should be at bottom.
SELECT *
FROM (SELECT (CASE WHEN cond1 THEN 1 ELSE 0 END +
CASE WHEN cond2 THEN 1 ELSE 0 END +
CASE WHEN cond2 THEN 1 ELSE 0 END +
...
CASE WHEN cond10 THEN 1 ELSE 0 END
) AS numMatches,
other_columns...
FROM mytable
) xxx
WHERE numMatches > 0
ORDER BY numMatches DESC
EDIT: This answer was posted before the question was modified with a concrete example. Marcelo's solution addresses the actual problem. On the other hand, my answer was giving priority to matches of specific fields.
You may want to try something like the following, using the same expressions in the ORDER BY clause as in your WHERE clause:
SELECT *
FROM your_table
WHERE field_1 = 100 OR
field_2 = 200 OR
field_3 = 300
ORDER BY field_1 = 100 DESC,
field_2 = 200 DESC,
field_3 = 300 DESC;
I've recently answered a similar question on Stack Overflow which you might be interested in checking out:
Is there a SQL technique for ordering by matching multiple criteria?
There are many options/answers possible. Best answer depends on size of the data, non-functional requirements, etc.
That said, what I would do is something like this (easy to read / debug):
Select * from
(Select *, iif(condition1 = bla, 1, 0) as match1, ..... , match1+match2...+match10 as totalmatchscore from sourcetable
where
condition1 = bla or
condition2 = bla2
....) as helperquery
order by helperquery.totalmatchscore desc
I could not get this to work for me on Oracle.
If using oracle, then this Order by Maximum condition match is a good solution.
Utilizes the case when language feature