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

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
...
)

Related

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.

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

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;

Returning the maximum of non-null columns ​from a table

I have a table with 4 columns, one of which is a non-null column, all others can be given a null value.
I just want a SELECT that returns results that have as many non-null columns as possible.
For example:
If I have 5 records in my Table, 1 of those records will have 3 columns with data, 2 of them will have 2 columns with data and 2 of them will have only 1 column with data. In my select, I want as a result only the first option: to bring me 3 columns with data. But it can be just 2 columns with data, it will be dynamic according to the table to be updated.
I'm using Oracle SQL.
One option is a conditional sort based on the count of non-null values in each row, and then a row-limiting clause (available since Oracle 12c). Assuming that the 3 nullable columns are col1, col2 and col3, that would be:
select *
from mytable
order by
case when col1 is null then 0 else 1 end
+ case when col2 is null then 0 else 1 end
+ case when col3 is null then 0 else 1 end desc
fetch first row with ties
If you are running an older version of Oracle, you can get the same result with window function rank():
select *
from (
select
t.*,
rank() over(order by
case when col1 is null then 0 else 1 end
+ case when col2 is null then 0 else 1 end
+ case when col3 is null then 0 else 1 end desc
) rn
from mytable t
) t
where rn = 1

Is it possible to force reutrn value from query when no rows found? [duplicate]

This question already has answers here:
Return a value if no record is found
(6 answers)
Get 0 value from a count with no rows
(6 answers)
Closed 7 years ago.
I have a simple query:
Select qty from X where id=....;
this query always return 0 or 1 row.
when it return 1 row everything works.
but if it return 0 rows my query fails as qty is used in calculations. (This is acatually a Sub query in Select statment).
I need somehow to make sure the query always return 1 row.
I tried:
Select coalesce(qty,0) from X where id=....;
but it doesn't help as if there are no rows the coalesce is useless.
if no row found it should give 0
How can I fix it?
You can do this:
SELECT COALESCE( (SELECT qty from X where id=....), 0)
if nothing is returned from the inner SELECT statement, COALESCE will give you 0 in the outer SELECT statement.
Select *.a from (
Select qty, 0 as priority from X where id=....
Union
Select 0, 1 as priority
) a
Order By a.priority Asc
Limit 1
This select basically ensures that at least one row is returned by adding an additional row to the end and by adding the limit statement we just return the first row.
So now there is the case where at least one row is found and the additional row is added to the end. In this case the first row found (see ->) will be returned due to the ascending order by priority:
qty priority
-> 1 0
3 0
4 0
. .
0 1
And then there is the case where no row is found but the additional row is returned:
qty priority
-> 0 1
try this.
SELECT COALESCE((SELECT qty
FROM x
WHERE id = #MyIdVar), 1)
If no records found then its return 'No rows found'
if not exists(Select * from table where condition=...)
Begin
Select * from table where condition=...
End
Else
Begin
Select 'No rows found'
End
Whenever you use this you will get record else no record found message.
Without using COALESCE()
select qty from X where id=1 UNION SELECT 0 order by qty desc limit 1
Demo

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