How to order by column if equal, order by another - sql

Really I don't know how to say it as question, but with example it will be clear to everyone, I have data retrieved from MYSQL database sorted by one of columns , my question if one of those values in this column is equal, I need to use another column to set who is show first.
col1 - col2
10 - 100
20 - 120
20 - 140
30 - 90
see here value 20 mentioned twice so I need to show the 20 with 140 before the 20 with 120 using MYSQL Query.

SELECT
*
FROM
MyTable
ORDER BY
Col1,
Col2 DESC

You can specify more than one column in the order by clause:
select * from table order by col1, col2;
This will order by col1, then order by col2 when col1 is equal. You can also specify ascending and descending separately for each column:
select * from table order by col1 asc, col2 desc;

You can add multiple columns in your order by clause.
select * from your_table
order by col1, col2 desc
The result will be ordered by the first column and if equal by the next and so forth

Related

How to select first-n/top-n rows from a query's resultant if its count is more than a given number?

I have a query that returns more than 1000 rows.
Step1:
with total_res as (
select table1.col1, table1.col2, table2.col3,... table2.coln
from table1 join table2
on table1.keycol=table2.keycol
where table1.col4='ABCD' and table2.col5 <= '02-02-2022'
order by table1.col1 desc)
In my requirement, I have to return the first 350rows by ordering col3 in desc if the output of the above query contain more than 1000rows.
So I added a row number column like below to add sequential numbers to the resulset from above.
Step2:
select col1, col2, col2...coln, ROW_NUMBER() OVER (ORDER BY col3 desc) as number from total_res;
What I don't understand now is how can I check if the output from step2 contains more than 350 rows and if so, select the first 350 rows.
Could anyone let me know how can I achieve this ? Or is there a better way to do it than using row_number ?
try like below in 2nd step check highest number>350 and then limit the value 350
with cte as
(
select col1, col2, col2...coln, ROW_NUMBER() OVER (ORDER BY col3 as number from total_res
) select * from cte
where 350 < ( select max(number) from cte)
order by number
limit 350

SQL DISTINCT based on a single column, but keep all columns as output

--mytable
col1 col2 col3
1 A red
2 A green
3 B purple
4 C blue
Let's call the table above mytable. I want to select only distinct values from col2:
SELECT DISTINCT
col2
FROM
mytable
When I do this the output looks like this, which is expected:
col2
A
B
C
but how do I perform the same type of query, yet keep all columns? The output would look like below. In essence I'm going through mytable looking at col2, and when there's multiple occurrences of col2 I'm only keeping the first row.
col1 col2 col3
1 A red
3 B purple
4 C blue
Do SQL functions (eg DISTINCT) have arguments I could set? I could imagine it to be something like KeepAllColumns = TRUE for this DISTINCT function? Or do I need to perform JOINs to get what I want?
You can use window functions, particularly row_number():
select t.*
from (select t.*, row_number() over (partition by col2 order by col2) as seqnum
from mytable t
) t
where seqnum = 1;
row_number() enumerates the rows, starting with "1". You can control whether you get the oldest, earliest, biggest, smallest . . .
You can use the QUALIFY clause in Teradata:
SELECT col1, col2, col3
FROM mytable
QUALIFY ROW_NUMBER() OVER(PARTITION BY col2 ORDER BY col2) = 1 -- Get 1st row per group
If you want to change the ordering for how to determine which col2 row to get, just change the expression in the ORDER BY.
With NOT EXISTS:
select m.* from mytable m
where not exists (
select 1 from mytable
where col2 = m.col2 and col1 < m.col1
)
This code will return the rows for which there is not another row with the same col2 and a smaller value in col1.

how to select min value from table if table has two unique values with rest of columns are identical

ex:Input
ID Col1 Col2 Col3
-- ---- ---- ----
1 a a sql
2 a a hive
Out put
ID Col1 Col2 Col3
-- ---- ---- ----
1 a a sql
Here my id value and Col3 values are unique but i need to filter on min id and populate all records.
I know below approach will work, but any best approach other than this please suggest
select Col1,Col2,min(ID) from table group by Col1,Col2;
and join this on ID,Col1,Col2
I think you want row_number():
select t.*
from (select t.*, row_number() over (partition by col1, col2 order by id) as seqnum
from t
) t
where seqnum = 1
It appears that Hive supports ROW_NUMBER. Though I’ve never used hive, other rdbms would use it like this to get the entire contents of the min row without needing to join (doesn’t suffer problems if there are repeated minimum values)
SELECT a.* FROM
(
SELECT *, ROW_NUMBER() OVER(ORDER BY id) rn FROM yourtable
) a
WHERE a.rn = 1
The inner query selects all the table data and establishes an incrementing counter in order of ID. It could be based on any column, the min ID (in this case) being row number 1. If you wanted the max, order by ID desc
If you want the number to restart for different values of another column (eg of ten of your Col3 were “sql” and twenty rows had “hive”) you an say PARTITION BY col3 ORDER BY id, and the row number will be a counter that increments for identical values of col3, restarting from 1 for each distinct value of col3

How to use group-by and get other rows results

Question: if this is my data:
col1,col2,col3,col4
===================
www.com,0,dangerous,reason A
www.com,1,dangerous 2,reason B
I want the a single result where column 2 value is max, so I will use in my select the Max(col2) function - but how can I get those corresponding col3 and col4 row ?
select
col1, max(col2), col3, col4
group by
col1
and ???
Thanks
Idan
You can use order by and limit to one row. The ANSI-standard syntax is:
select t.*
from t
order by t.col2 desc
fetch first 1 row only;
Not all databases support the fetch first clause, so you might have to use select top 1, limit, or some other construct.
You can use where in select statement
Like
Select * from table name where col2=max(col2)
You can get max column entire row with single value
If the column col2 which contain same value like 1,1,2,2 at this time above query return the 2 rows. At that time if you want single row you want to use this
Select * from table name where col2=max(col2) fetch first 1 row only
Might be this helpful

Select 10 records after id=somevalue, (id>somevalue) and select first 10 records if id=somevalue doesn't exist

I have an sql query which selects 10 records after id= somevalue, but i want to select the first 10 records if the record doesnt exist. Query is in below structure.
SELECT * FROM TABLE WHERE ID > x ORDER BY METRIC LIMIT 10
Provided, id here is a varchar field which is sorted based on some field.
This comes close to what you want:
SELECT *
FROM TABLE
ORDER BY (CASE WHEN ID > X THEN 1 ELSE 0 END) DESC,
METRIC
LIMIT 10
It will always return 10 records (assuming you have at least 10 records in the table). It will put the ones with id > x first. If there are not enough of those, then it will fill in with other records.
This will also work:
SELECT TOP 10 col1, col2
FROM #yourtable
WHERE col1 > #ID
UNION ALL
SELECT TOP 10 col1, col2
FROM #yourtable
WHERE NOT EXISTS (SELECT * FROM #yourtable WHERE col1 = #ID)
However, this assumes you have an ID that you can query on using greater than/less than to retrieve the desired "next ten" records. Also, you would probably need to add an "ORDER BY" clause to ensure the records have the desired values.