What does ORDER BY 5 DESC mean? - sql-server-2005

SELECT Departamentos.Nome_Dep,
Funcionarios.Nome AS Funcionario,
Funcionarios.Salario,
AVG(Funcionarios.Salario) OVER(PARTITION BY Departamentos.Nome_Dep) "Média por Departamento"
Salario - AVG(Funcionarios.Salario) OVER(PARTITION BY Departamentos.Nome_Dep) "Diferença de Salário" FROM Funcionarios
INNER JOIN Departamentos
ON Funcionarios.ID_Dep = Departamentos.ID
ORDER BY 5 DESC
The Order By 5 is throwing me off. I've never anything like it. Order By [colunmname] yes, but Order By [number], never seen before. I pulled this off an article.
Note: This is T-SQL.
Source: Window Functions in SQL Server 2005, 2008, 2012

This will order by the 5th field in this SELECT statement

Order by the 5th column in the result set.

The number represents the index of the column within your select list.
Source: http://mattberseth.com/blog/2007/05/quick_tip_order_by_1_descendin.html

Order by fifth column in the result set descending.

It is the SORTING BY RELATIVE POSITION.
You can use the SQL ORDER BY clause to sort by relative position in the result set, where the first field in the result set is 1. The next field is 2, and so on.
Here in this case Order by 5th field in the result set.
Go through http://www.techonthenet.com/sql/order_by.php
about sql order by.

Useful when a similar column name has become a calcuated output field,
In the following example, it would be confusing if say 'order by numberofVioation' as this column name has just become the name of a query output SUM field (of the same old column data)
So it become useful in calculated output field
Example:
Original fields:
name| Type| RiskLevel| Date| results| violations|
/* now add an extra Sum of Violation for each type, pls note 'order by 2 desc' refers to order by the 2nd queried column, ie hi to low */
select Type, sum(numberOfViolations) as numberOfViolations
from restaurantsTable
group by Type
order by 2 desc

Order by 5th field in the result set.

Related

How to determine the order of the result from my postgres query?

I have the following query:
SELECT
time as "time",
case
when tag = 'KEB1.DB_BP.01.STATUS.SOC' THEN 'SOC'
when tag = 'KEB1.DB_BP.01.STATUS.SOH' THEN 'SOH'
end as "tag",
value as "value"
FROM metrics
WHERE
("time" BETWEEN '2021-07-02T10:39:47.266Z' AND '2021-07-09T10:39:47.266Z') AND
(container = '1234') AND
(tag = 'KEB1.DB_BP.01.STATUS.SOC' OR tag = 'KEB1.DB_BP.01.STATUS.SOH')
GROUP BY 1, 2, 3
ORDER BY time desc
LIMIT 2
This is giving me the result:
Sometimes the order changes of the result changes from SOH -> SOC or from SOC -> SOH. I'm trying to modify my query so I always get SOH first and than SOC.. How can I achieve this?
You have two times that are identical. The order by is only using time as a key. When the key values are identical, the resulting order for those keys is arbitrary and indeterminate. In can change from one execution to the next.
To prevent this, add an additional column to the order by so each row is unique. In this case that would seem to be tag:
order by "time", tag
You want to show the two most recent rows. In your example these have the same date/time but they can probably also differ. In order to find the two most recent rows you had to apply an ORDER BY clause.
You want to show the two rows in another order, however, so you must place an additional ORDER BY in your query. This is done by selecting from your query result (i.e. putting your query into a subquery):
select *
from ( <your query here> ) myquery
order by tag desc;
Try this:
order by 1 desc, 2
(order by first column descending and by the second column)

SQL Query - how do I order part of my data in alphabetical order, and part by id

I have a small piece of data (15 records) where part of it I want ordered in alphabetical order, and part of it ordered by ID
Image 1 shows my data in the original order
After doing the query SELECT * FROM tableName ORDER BY code;
Image 2 shows my data now in alphabetical order, which is great however I would like the top 2 records to be ordered by id
Image 3 shows how I would like my data to look
Could someone help with my query please?
i assumed id is an integer. You can use conditional CASE in the ORDER BY clause.
Note for the first expression case when code in ('LUX-INT', 'LUX-CONT') then -id end desc, it will return id or NULL. As NULL will comes first in ORDER BY, I use DESC and negate the id value so that id is in ascending order
order by case when code in ('LUX-INT', 'LUX-CONT') then -id end desc, code
use case when
SELECT * FROM tableName ORDER BY case when code in ('LUX INT','LUX-CONT') then id else code end
I would write this as:
order by (case when code in ('LUX-INT', 'LUX-CONT') then 1 else 2 end), -- put the special codes first
(case when code in ('LUX-INT', 'LUX-CONT') then code end), -- order them alphabetically
id -- order the rest by id
This works regardless of the types and collations of the underlying columns.

Access VBA: Get difference in value between current and previous record

I have made report based on query according to this link:
http://www.techonthenet.com/access/queries/max_query2.php
It gives me list of records with values:
(primaryKey)
ID.......FirstNum....SecNum.....Diameter.....Owner
1........100200.......01...............150..............Peter
2........100200.......02...............138..............Peter
3........100300.......07...............112..............John
Query sorts records in descending order by Diametral. I want make new column which will count difference between first and second record, then between third and second and so on. Like this:
(primaryKey)
ID.......FirstNum....SecNum.....Diameter.....DiffDiametral.....Owner
1........100200.......01...............150.......................................Peter
2........100200.......02...............138.............12......................Peter
3........100300.......07...............112.............26.....................John
What should I write into RowSource or DataSource for DiffDiametral to get these values? How can I avoid error for first line, where is not previous value which I want substract from?
I tried to solve it according to this link:
http://support.microsoft.com/kb/101081/en-us
but I did not solve it. Simply I dont know how I can refer previous value of Diameter to count difference.
Based on your information, a subquery should do it. Just substitute your actual table name for tblDiameters.
SELECT C.ID, C.FirstNum, C.SecNum, C.Diameter, C.Owner,
(SELECT TOP 1 P.Diameter
FROM tblDiameters AS P
WHERE P.Diameter < C.Diameter
ORDER BY P.Diameter DESC )
- C.Diameter AS DiffDiameter
FROM tblDiameters AS C

SQL (Mysql) order problem

I have the following query:
SELECT a.field_eventid_key_value, a.field_showdate_value, b.nid , c.nid AS CNID
FROM content_type_vorfuehrung AS a
LEFT JOIN content_type_movies as b ON a.field_eventid_key_value = b.field_eventid_value
LEFT JOIN content_type_sonderveranstaltung as c ON a.field_eventid_key_value = c.field_sonderveranstaltungid_value
WHERE /* something */
GROUP BY a.field_eventid_key_value, a.field_showdate_value,
ORDER BY a.field_showdate_value ASC,a.field_showtime_value ASC
(where clause removed since it's irrelevant to the question)
This pulls data from 3 different tables and sorts it according to the "showdate" field in the first table. This is used in a PHP function that returns an array with the results.
Now there is a new requirement: The table "content_type_movies" in this query has a field that's supposed to be a boolean (actually it's an int with a value of either "0" oder "1"). This field is supposed to override the chronological ordering - that is, results where the field is "true" (or "1" respectively) should appear at the beginning of the result array (with the remaining entries ordered chronologically as before).
Is this at all possible with a single query ?
Thank you in advance for your time,
eike
You can use:
ORDER BY b.MyIntField DESC,
a.field_showdate_value,
a.field_showtime_value
where MyIntField is the field that is either 1 or 0 that you want to sort first.
ORDER BY a.content_type_movies DESC, /*then other fields*/ a.field_showdate_value ASC,a.field_showtime_value ASC
that should place all rows with content_type_movies=1 first then others.

mysql show rows in order from highest value to lowest value

I have a table that contains a column named views. Each time the user refreshes the page, it updates the view count +1.
What im trying to do, is create a mysql query to output the list of rows based on their views count, from highest to lowest.
this is what i thought would work
SELECT * FROM picdb ORDER BY views DESC LIMIT 10
even when i view it ASCENDING, its all out of whack.
thoughts?
EDIT
the column type is TEXT
SOLVED changed column type to INT and it works fine now. Thanks for pointing it out.
If your column type is TEXT, the default sorting behavior treats the data as strings, and therefore sorts them alphabetically (not numerically).
Change your column type to a number type, and it will sort correctly.
SELECT
*
FROM
tbl
ORDER BY
CAST(views AS UNSIGNED) DESC
LIMIT
10
Might do the trick. The real question is why you have a column containing integers with the text type?
select a,b,CAST(views AS UNSIGNED) c from picdb order by c desc limit 10
This looks like the classic alphanumeric sort problem. If the column type is text, then you are probably seeing order like 1, 10, 15, 20, 3. In other words, it’s sorting by the text value instead of the integer value.
You could change the column to a numeric type, or you could do:
SELECT * FROM picdb ORDER BY CONVERT(views, UNSIGNED INTEGER) DESC LIMIT 10
However, this would not be able to take advantage of any index on the views column. It would be better to change the column to a numeric type if that is indeed what it represents.
If you want to show your table rows from higher value to lower value then use this query.
query = "SELECT * FROM CurrencyTable ORDER BY CAST(currency_rate AS UNSIGNED) DESC";
And if you want to show rows from lower value to higher value then use this query
query-2 = "SELECT * FROM CurrencyTable ORDER BY CAST(currency_rate AS UNSIGNED) ASC";