SQL: Order By The Sequence in the "IN" Statement [duplicate] - sql

This question already has answers here:
Ordering SQL Server results by IN clause
(3 answers)
Closed 7 years ago.
The Base Data:
Note this is all SQL Server.
Okay so the base table will look something like this(call it NameTable):
ID | Name
___________________
1 | Randy
2 | Kenny
3 | Stan
4 | Kyle
5 | Cartman
Now I will run a SQL query:
SELECT * FROM [NameTable] WHERE Name IN ("Kyle", "Stan", "Kenny", "Cartman", "Randy")
The Current Result:
ID | Name
___________________
1 | Randy
2 | Kenny
3 | Stan
4 | Kyle
5 | Cartman
This is as expected. And that is fine, but what I need is to order the data by the order they appear in the IN statement.
So in this case: Kyle, Stan, Kenny, Cartman, Randy.
Take special note that this is NOT going to work with standard order by, since it won't necessarily be in alphabetic order
The Needed Result:
ID | Name
___________________
4 | Kyle
3 | Stan
2 | Kenny
5 | Cartman
1 | Randy
Question
Basically the order of the items in the IN clause is the order I need the names by.
How should I adjust the select query to achieve this result? Is it even possible?
PS: I did not think a sqlfiddle necessary since the data is pretty straight forward, but I will add one if the question is still unclear?
Also I saw some other posts on this, but they weren't for SQL Server.

You can do something like:
SELECT *
FROM dbo.NameTable
ORDER BY CASE WHEN Name = 'Kyle' THEN 1
WHEN Name = 'Stan' THEN 2
WHEN Name = 'Kenny' THEN 3
WHEN Name = 'Cartman' THEN 4
WHEN Name = 'Randy' THEN 5
ELSE 6 END ASC

Related

SQL select id from table [duplicate]

This question already has answers here:
What is the default SQL result sort order with 'select *'? [duplicate]
(2 answers)
Closed 3 months ago.
I run the simplest query:
select id from table_xx where name='aaa'
toward this table:
table_xx
-----------------------------
| id | name |
-----------------------------
| 1 | aaa |
| 2 | bbb |
| 3 | aaa |
------------------------------
Note: id is a primary key.
so if I run code like this:
result = execute_query(query)
print (result[0][0])
Will it ALWAYS return the smallest id first in dataset? which is id=1
or is there a chance that id=3 will be returned as the first row in dataset
There is no "default order". You will only get a specific sort order if you use order by.
If there is no order by, the database is free to return the rows in any order it thinks is most efficient.
P.S. original detailed answer
Adding a sort clause to your sql query would guarantee this

Oracle database - select max sum per category [duplicate]

This question already has answers here:
Fetch the rows which have the Max value for a column for each distinct value of another column
(35 answers)
Select First Row of Every Group in sql [duplicate]
(2 answers)
Return row with the max value of one column per group [duplicate]
(3 answers)
SQL Selecting dates with maximum sale for each department [duplicate]
(3 answers)
SQL: getting the max value of one column and the corresponding other columns [duplicate]
(2 answers)
Closed 1 year ago.
I am trying to write a query in Oracle which will return id of the driver who transported the most goods in range of a single goods category.
So far my query is as follows:
SELECT
truckset.driver_id, cargo.additional_liecence_id,
SUM(order_details.cargo_amount) as cargo_sum
FROM
order_details
INNER JOIN
truckset on truckset.order_id = order_details.order_id
INNER JOIN
cargo on order_details.cargo_id=cargo.id
WHERE
cargo.additional_liecence_id IS NOT NULL
GROUP BY
truckset.driver_id, cargo.additional_liecence_id
ORDER BY
SUM(order_details.cargo_amount) DESC;
And it returns:
| DRIVER_ID | ADDITIONAL_LICENCE_ID | CARGO_SUM |
| 14 | 8 | 174 |
| 17 | 8 | 144 |
| 7 | 5 | 70 |
| 11 | 5 | 50 |
| 7 | 6 | 50 |
while I expect something like this:
| DRIVER_ID | ADDITIONAL_LICENCE_ID | CARGO_SUM |
| 14 | 8 | 174 |
| 7 | 5 | 70 |
| 7 | 6 | 50 |
I don't have your database, so the syntax may not be exact, but you want to use SQL Analytics functions. You want to do something like this, where you can tweak the syntax in a live database:
WITH T AS (
SELECT truckset.driver_id, cargo.additional_liecence_id, SUM(order_details.cargo_amount) as cargo_sum,
ROW_NUMBER() OVER (
PARTITION BY driver_id, additinoal_liecence_id
ORDER BY cargo_sum
) AS ROW_NUMBER -- ADD THIS 'COLUMN' TO YOUR SELECT CLAUSE.
FROM order_details
INNER JOIN truckset on truckset.order_id = order_details.order_id
INNER JOIN cargo on order_details.cargo_id=cargo.id
WHERE cargo.additional_liecence_id IS NOT NULL
GROUP BY truckset.driver_id, cargo.additional_liecence_id
ORDER BY SUM(order_details.cargo_amount) DESC
)
SELECT * FROM T WHERE ROW_NUMBER = 1;
I wrote a whole page on SQL Analytics functions from the Oracle documentation when I taught them in graduate school. It is here:
http://www.qa76.net/sql_analytics
It is very nicely colorized, if I do say so myself :), which makes it much more readable then the original Oracle documentation from which it comes. About two thirds of the way down the page it discusses the ROW_NUMBER() function.
There's probably an even more elegant and expressive way to do this with different SQL Analytics functions, but this should get you started.
Enjoy!
(Edit: My thanks to 'MT0' in the comments for addressing the syntax issue. Changed it to use 'WITH' and filter on that.)

How does DISTINCT interact with ORDER BY?

Consider the two tables below:
user:
ID | name
---+--------
1 | Alice
2 | Bob
3 | Charlie
event:
order | user
------+------------
1 | 1 (Alice)
2 | 2 (Bob)
3 | 3 (Charlie)
4 | 3 (Charlie)
5 | 2 (Bob)
6 | 1 (Alice)
If I run the following query:
SELECT DISTINCT user FROM event ORDER BY "order" DESC;
will it be guaranteed that I get the results in the following order?
1 (Alice)
2 (Bob)
3 (Charlie)
If the three last rows of event are selected, I know this is the order I get, because it would be ordering 4, 5, 6 in descending order. But if the first three rows are selected, and then DISTINCT prevents the last tree to be loaded for consideration, I would get it in reversed order.
Is this behavior well defined in SQL? Which of the two will happen? What about in SQLite?
No, it will not be guaranteed.
Find Itzik Ben-Gan's Logical Query Processing Phases poster for MS SQL. It migrates over many sites, currently found at https://accessexperts.com/wp-content/uploads/2015/07/Logical-Query-Processing-Poster.pdf .
DISTINCT preceeds ORDER BY .. TOP and Sql Server is free to return any of 1 | 1 (Alice) or 6 | 1 (Alice) rows for Alice. So any of (1,2,3), (1,4,5) an so on are valid results of DISTINCT.
Here's a query solution that I believe solves your problem.
SELECT
MAX([order]) AS MaxOrd
, [user]
FROM Event
GROUP BY [User]
ORDER BY MaxOrd DESC

Add counter field in select result in Access Query [duplicate]

This question already has an answer here:
Access query producing results like ROW_NUMBER() in T-SQL
(1 answer)
Closed 8 years ago.
I have a table with some field.
name, stud_id
ali | 100
has | 230
mah | 300
I want to get some of record and show a row field beside of record.
1 | ali | 100
2 | has | 230
3 | mah | 300
How I can do it.
Thanks.
Select (select count(*) from Table1 A where A.stud_id>=B.stud_id) as RowNo, B.*
from Table1 as B
order by A.stud_id
MS-ACCESS does not have rownum function, so this might help you.
But your ID need to be sortable and unique.

SQL Server 2008 pivot query gone wrong with column name

I have some problems regarding a pivot query. I am new to this. So look for something in the internet so I found dozens of them. So I decided to follow this Link. Been practice but seems like I ran into some obvious error.
My code is:
select
risk, [Quick] AS Quick, [Brown] AS Brown, [Fox] AS Fox
from
(select risk, site
from tst) as ps
PIVOT
(
count(risk)
for site in ([Brown], [Brown], [Fox])
) AS pvt
But it is throwing an error:
Invalid column name 'risk'.
Basically I want to have an output like this:
|Foo | Quick | Brown | Fox |
| 1 | 10 | 3 | 2 |
| 2 | 5 | 4 | 4 |
| 3 | 4 | 1 | 5 |
| 4 | 2 | 3 | 7 |
| 5 | 3 | 2 | 1 |
Something like that. Just counting how many there is in a specific number. Any help would be much appreciated. Thanks
The problem with your existing query is you are using the column risk in your final select list as well as inside of the aggregate function. Once you've counted the risk values for each site this is not available to display.
To get around this you can add a second version of the risk column to your subquery similar to the following. You then count this other column of risk and display one in the final select:
select risk, [ADAB] AS ADAB, [Bahrain] AS Bahrain, [Thumrait] AS Thumrait
from
(
select risk, piv_risk = risk, site
from qcqcif
) as ps
PIVOT
(
count(piv_risk)
for site in ([ADAB], [Bahrain], [Thumrait])
) AS pvt;
See SQL Fiddle with Demo