How to use max function with select top in sql - sql

I have a table, lets call it TempAccount, with a column named AccountID. It contains numbers from 1,2,3...and so on.
My requirement is that I should select the maximum value from the top 10 AccountIDs.
I know I can do it by creating a temp table and inserting the top 10 values in it and then select the maximum value out of that table. But I was hoping if there is any direct query I can use to achieve this.
Something like MAX(SELECT TOP 10 AccountID FROM TempAccount)
What is the best way I can achieve this?
Note: I am using SQL Server 2012

You can use CTE query. Example:
WITH CTEQuery (AccountId) AS (
SELECT TOP 10 AccountId
FROM TempAccount
ORDER BY AccountId
)
SELECT MAX(AccountId)
FROM CTEQuery

Do the TOP 10 in a derived table, then use MAX on its result. Something like:
select max(dt.col1)
from
(
select top 10 col1
from table
where ...
order by ...
) dt

Related

SQL Select top 100 columns be specific column names or indices

This works to select top 100 columns, but it gives me all of the columns
select top 100 * from dw.test
This works, but it gives me endless rows,
select Slot, ID from dw.test
I need to select top 100 rows that only show these two columns Slot, ID
I cannot get it to work no matter how I try to combine them,
Please help create this query. Thank you
try it
select TOP(100) Slot, ID from dw.test ORDER BY Slot, ID DESC
It's not clear to me which RDBMS is being used, but one of the following should work:
SELECT TOP(100) Slot, ID FROM dw.test;
Limit instead?
SELECT Slot, ID FROM dw.test LIMIT 100;

How to select records in the order they were inserted, and then group them by a type

I have a query I can not seem to get to work.
I have a table like this:
ThingID, FK_ThingTypeID, Etc...
And I want to select records in the order they were inserted, but group them by type. So if the data looks in the table is in the following order:
ThingID, FK_ThingTypeID
1 1
2 2
3 1
4 1
I want to get select the records like this:
ThingID, FK_ThingTypeID
1 1
3 1
4 1
2 2
So they are in the order they were added, but grouped by type.
I have tried using ORDER BY and GROUP BY for this but no combination of what I try works, and all the GROUP BY examples I see are working with aggregate functions. I am not interested in counts or max etc.. I just want to order the records as above. I have tried just using an ORDER BY ThingID, FK_ThingTypeID, but this just lists them by ID and does not group by the types. There are a stack more columns in the table and using GROUP BY requires that I add all these, and then it doesn't work anyway.
Can anyone give an example of an approach to achieve the result I am looking for?
Thanks for your time.
Thanks for those that responded.
Here was the solution:
SELECT
t.*
FROM
Thing t
ORDER BY
(
SELECT
min(ref.ThingID)
FROM Thing ref
WHERE
ref.ThingTypeID = t.ThingTypeID
),
t.ThingID
May be this query is helpful for you as per my understanding:
select * from table order by rownum, FK_ThingTypeID
You can try below query:
select ROW_NUMBER() OVER(
ORDER BY THINGID) AS RowNum, FK_ThingTypeID from table
Your query seems simple so am sure someone will be able to help.
Gotta love Stack Overflow.
I had a go not sure whether this is what you are after?
Apologies if not
SELECT ThingID,FK_ThingTypeID
FROM Table
ORDER BY FK_ThingTypeID, ThingID

How could I query from the first n rows using SQL?

For example, I would like to query from the first 10 rows, how could I achieve that. (Not get the first 10 of the query results).
I tried using 'limit' first then 'where' but it doesn't work.
If I understand correctly you first want to fetch 10 rows of one query, then search within those 10 rows for data. To do that you can use a subquery:
SELECT *
FROM (SELECT *
FROM YOUR_TABLE yt
ORDER BY yt.SOME_COLUMN
LIMIT 10) sq
WHERE sq.SOME_OTHER_COLUMN > 25;
Best of luck.
Based on your sort criteria you can create a SQL like this
SELECT column1, column2, ...
FROM your table
ORDER BY sort column
LIMIT 10
This will give you the top 10 rows from your table based on your sort column

Select into with max()

I have a basic query I use to determine the max value of a column in a table:
select A.revenue_code_id, max(A.revenue_code_version) from rev_code_lookup A
group by A.revenue_code_id
This results in ~580 rows (the entire table has over 2400 rows).
This works just fine for my query results but what I don't know is how to insert the 580 rows into a new able based on the max value. I realize this isn't the right code but what I am thinking of would look something like this:
select * into new_table from rev_code_lookup where max(revenue_code_version)
You can use the row_number() function to get the data you want. Combine with the other answer to insert the results into a table (I've made up a couple of extra columns as an example):
Select
x.revenue_code_id,
x.revenue_code_version,
x.update_timestamp,
x.updated_by
From (
Select
revenue_code_id,
revenue_code_version,
update_timestamp,
updated_by,
row_number() over (partition by revenue_code_id Order By revenue_code_version Desc) as rn
From
revenue_code_lookup
) x
Where
x.rn = 1
Example Fiddle
The insert in another table is always the same way, no matter the complexity of your select:
insert into table
[unbeliavablycomplicatedselecthere]
So in your case:
insert into new_table
select A.revenue_code_id, max(A.revenue_code_version) from rev_code_lookup A
group by A.revenue_code_id
Similarly, if you need to create a brand new table, do this first:
CREATE TABLE new_table
AS
select A.revenue_code_id, max(A.revenue_code_version) from rev_code_lookup A
group by A.revenue_code_id
This will create the corresponding table schema and then you can execute the previous query to insert the data.

Most efficient way to select 1st and last element, SQLite?

What is the most efficient way to select the first and last element only, from a column in SQLite?
The first and last element from a row?
SELECT column1, columnN
FROM mytable;
I think you must mean the first and last element from a column:
SELECT MIN(column1) AS First,
MAX(column1) AS Last
FROM mytable;
See http://www.sqlite.org/lang_aggfunc.html for MIN() and MAX().
I'm using First and Last as column aliases.
if it's just one column:
SELECT min(column) as first, max(column) as last FROM table
if you want to select whole row:
SELECT 'first',* FROM table ORDER BY column DESC LIMIT 1
UNION
SELECT 'last',* FROM table ORDER BY column ASC LIMIT 1
The most efficient way would be to know what those fields were called and simply select them.
SELECT `first_field`, `last_field` FROM `table`;
Probably like this:
SELECT dbo.Table.FirstCol, dbo.Table.LastCol FROM Table
You get minor efficiency enhancements from specifying the table name and schema.
First: MIN() and MAX() on a text column gives AAAA and TTTT results which are not the first and last entries in my test table. They are the minimum and maximum values as mentioned.
I tried this (with .stats on) on my table which has over 94 million records:
select * from
(select col1 from mitable limit 1)
union
select * from
(select col1 from mitable limit 1 offset
(select count(0) from mitable) -1);
But it uses up a lot of virtual machine steps (281,624,718).
Then this which is much more straightforward (which works if the table was created without WITHOUT ROWID) [sql keywords are in capitals]:
SELECT col1 FROM mitable
WHERE ROWID = (SELECT MIN(ROWID) FROM mitable)
OR ROWID = (SELECT MAX(ROWID) FROM mitable);
That ran with 55 virtual machine steps on the same table and produced the same answer.
min()/max() approach is wrong. It is only correct, if the values are ascending only. I needed something liket this for currency rates, which are random raising and falling.
This is my solution:
select st.*
from stats_ticker st,
(
select min(rowid) as first, max(rowid) as last --here is magic part 1
from stats_ticker
-- next line is just a filter I need in my case.
-- if you want first/last of the whole table leave it out.
where timeutc between datetime('now', '-1 days') and datetime('now')
) firstlast
WHERE
st.rowid = firstlast.first --and these two rows do magic part 2
OR st.rowid = firstlast.last
ORDER BY st.rowid;
magic part 1: the subselect results in a single row with the columns first,last containing rowid's.
magic part 2 easy to filter on those two rowid's.
This is the best solution I've come up so far. Hope you like it.
We can do that by the help of Sql Aggregate function, like Max and Min. These are the two aggregate function which help you to get last and first element from data table .
Select max (column_name ), min(column name) from table name
Max will give you the max value means last value and min will give you the min value means it will give you the First value, from the specific table.