How to find the Second value from a table.? - sql

I have One table with StatusID in StatusHistory Table. One customer could be multiple statusID. I need to find just previous statusID that mean the second Status ID which just befor he was hold.
I am getting current one this bellow way:
SELECT top 1 StatusIDHeld
FROM dbo.UserStatusHistory
WHERE userid=2154
ORDER BY tatusChangedOn DESC
Question:
I need 2nd statusID means just previous statusID
How to find the Second value(StatusID) from a table.?

select StatusIDHeld
from
(select
StatusIDHeld,
ROW_NUMBER () over (order by tatusChangedOn DESC) as num
from dbo.UserStatusHistory
where userid=2154
) T
where T.num = 2

There's nothing like second value of table. It depends on many factors, like indexes, etc.
To be able to get 1., 2. or n-th record depending on sort order, use ROW_NUMBER() function.
SELECT StatusIDHeld
FROM
(
SELECT StatusIDHeld, ROW_NUMBER () OVER(ORDER by StatusIDHeld) as RowNo
FROM UserStatusHistory
) AS t
where t.RowNo = 2
Another way is to use TOP instruction twice:
SELECT TOP(1) StatusIDHeld
FROM (
SELECT TOP(2) StatusIDHeld
FROM UserStatusHistory
WHERE userid=2154
ORDER BY tatusChangedOn ASC
) AS t
ORDER BY StatusIDHeld DESC

One way to do this is to fetch the first 2, and then take the second one of them:
select top 1 StatusIDHeld from (
select top 2 StatusIDHeld, StatusChangedOn
from dbo.UserStatusHistory
order by StatusChangedOn DESC
) TMP order by StatusChangedOn ASC

You need to offset your query reset by 1.
Please try this:
select StatusIDHeld from dbo.UserStatusHistory order by tatusChangedOn DESC Limit 1 OFFSET 1;

Related

Problem with returning nth row from MS Access table

I'm trying to select the nth row of a table in MS Access (Office 365). I've seen both of the following solutions:
https://stackoverflow.com/a/45031166/1907765
https://stackoverflow.com/a/44891583/1907765
And neither of them have worked for me. When I wrote a query based on these answers, the query returned the last n rows in a table, and then selected the first result in that. E.g. if I was looking to select the 3rd row, it would select the 3rd-to-last row. Here's my query:
SELECT TOP 1 Sense.SenseID
FROM
(
SELECT TOP 3 Sense.SenseID
FROM Sense
ORDER BY Sense.SenseID DESC
)
ORDER BY Sense.SenseID ASC
Any idea what I'm doing wrong, and how to generate the correct result?
The order bys should be reversed:
SELECT TOP 1
s.SenseID
FROM
(SELECT TOP 3 s.SenseID
FROM Sense AS
ORDER BY s.SenseID Asc) AS s
ORDER BY
s.SenseID Desc;
You need a table alias so the syntax is correct. Try this:
SELECT TOP 1 s.SenseID
FROM (SELECT TOP 3 s.SenseID
FROM Sense as s
ORDER BY s.SenseID DESC
) as s
ORDER BY s.SenseID ASC;
This assumes that Sense.SenseID is unique -- but that seems like a reasonable assumption.

Select Minimum value of column A where Column B=1

I have this table AVERAGE
I want to
select * from table where VhrNum=MIN(VhrNum) and EmptyOrNot=1
I've Tried this query but it's not working
select *
from Average
where Itmnum='1'
and VhrNum = (
select MIN(VhrNum)
from (
select *
from Average
where EmptyOrNot = '1'
)
)
In my case it's should select the third row
Why not just take the top 1 row and order by by the column?
SELECT TOP 1 *
FROM [table]
WHERE EmptyOrNot=1
ORDER BY VhrNum
Use TOP 1 with ORDER BY
select Top 1 * from table where EmptyOrNot=1
Order by VhrNum ASC
If you more than one record with min VhrNum value and you want all the tie records then use TOP 1 WITH TIES
select Top 1 With Ties * from table where EmptyOrNot=1
Order by VhrNum ASC
You can try like this
SELECT MIN(VhrNum) FROM table_name where EmptyOrNot=1;
Aggregate functions need a GROUP BY - or you could ORDER BY and select the first.
Aggregate won't let you do a SELECT *, which isn't really good practice anyway, and aggregate makes it clearer that you're actually trying to get the MIN of this. TOP 1/ORDER BY would let you do a SELECT *, but may be less immediately clear that all you're really trying to get is the MIN(VhrNum).
Aggregate:
SELECT MIN(VhrNum)
FROM Average
WHERE EmptyOrNot = 1
GROUP BY EmptyOrNot
Top:
SELECT TOP(1) VhrNum, *
FROM Average
WHERE EmptyOrNot = 1
ORDER BY VhrNum ASC
You can try this:
select top 1 * from table where VhrNum= (select min(VhrNum) from table);

How to use ROWNUM for a maximum and another minimum ordering in ORACLE?

Currently i am trying to output the top row for 2 condition. One is max and one is min.
Current code
Select *
from (MY SELECT STATEMENT order by A desc)
where ROWNUM <= 1
UPDATE
I am now able to do for both condition. But i need the A to be the highest, if same then check for the B lowest.
E.g Lets say there is 2 rows, Both A is 100 and B is 50 for one and 60 for other.
In this case the 100:50 shld be choose because A is same then B is lowest.
E.g
Lets say there is 2 rows, A is 100 for one and 90 for other, since one is higher no need to check for B.
I tried using max and min but this method seems to work better, any suggestions
Well, after your clarification, you are looking for one record. With Max A. And the smallest B, in case there is more than one record with MAX A. This is simply:
Select *
from (MY SELECT STATEMENT order by A desc, B)
where ROWNUM = 1;
This sorts by A descending first, so you get all maximal A records first. Then it sorts by B, so inside each A group you get the least B first. This gives you the desired A record first, no matter if the found A is unique or not.
or avoid the vagaries of rownun and go for row_number() instead:
SELECT
*
FROM (
SELECT
*
, ROW_NUMBER (ORDER BY A DESC) adesc
, ROW_NUMBER (ORDER BY B ASC) basc
FROM SomeQuery
)
WHERE adesc = 1
OR basc = 1
footnote: select * is a convenience only, please replace with the actual columns required along with table names etc.
Try this if that works
Select *
from (MY SELECT STATEMENT order by A desc)
where ROWNUM <= 1
union
Select *
from (MY SELECT STATEMENT order by A asc)
where ROWNUM <= 1
SELECT * FROM
(Select foo.*, 0 as union_order
from (MY SELECT STATEMENT order by A desc) foo
where ROWNUM <= 1
UNION
Select foo.*, 1
from (MY SELECT STATEMENT order by B asc) foo
where ROWNUM <= 1)
ORDER BY
union_order

Select 2nd and 3rd newest row in an SQL table

i'm currently developing a news-site.
So here is the problem. I want to select the 2nd and 3rd row in a TOP 3.
SELECT TOP 3 * FROM News ORDER BY Date DESC;
I want to remove the 1st row and only return the 2nd and 3rd row.
Can anyone help?
Try this:
SELECT TOP 2 FROM
( SELECT TOP 3 * FROM News ORDER BY Date DESC ) xx
ORDER BY Date
SQLFiddle: http://www.sqlfiddle.com/#!3/dbb7e/5
You can also do this generically using window functions:
select n.*
from (SELECT n.*, row_number() over (order by date desc) as seqnum
FROM News n
) n
where n.seqnum >= 2 and n.seqnum <= 3;
I just offer this as a general solution. You can also ensure that you get everything from the second date (in case there are more than two items on that date) by using dense_rank() rather than row_number().
If you know that no two dates will be the same, you could add
where date not in (select max(date) from News)
Or you could look at rowid if you know that the first item will have rowid=0, for example if you created a temp table with the results of your initial query.
I assume, you somehow know what you Top 3 news are by ordering by date descending.
Therfore you should use the LIMIT clause with an OFFSET [For sqlite]
SELECT * FROM News ORDER BY Date DESC LIMIT 2 OFFSET 1;
Select top 2 * from News cross apply (select top 3 from news order by date desc)x

Order by clause is changing my result set

I know why it's happening but I want to find a way around it if possible.
For example I have 4 rows in my database and each has a datetime (which are all different). What I want to do is get the latest 2 rows but use ascending order, so that the oldest is at the top of the result set.
I currently am using
SELECT TOP 2 *
FROM mytable
WHERE someid = #something
ORDER BY added DESC
This gets me the correct rows but in the wrong order. If I change the DESC to ASC it gets the right order, but the older two of the four rows. This all makes sense to me but is there a way around it?
EDIT: Solved with Elliot's answer below. The syntax would not work without setting an alias for the derived table however. Here is the result
SELECT * FROM
(SELECT TOP 2 * FROM mytable WHERE someid = #something ORDER BY added DESC) AS tbl
ORDER BY tbl.added ASC
I'd think one brute-force solution would be:
SELECT *
FROM (SELECT TOP 2 * FROM mytable WHERE someid = #something ORDER BY added DESC)
ORDER BY added
This will allow "top 2 per something" with a PARTITION BY added to the OVER clause
SELECT *
FROM
(
SELECT *, ROW_NUMBER() OVER (ORDER BY added DESC) as rn
FROM mytable
WHERE someid = #something
) foo
WHERE rn <= 2
ORDER BY added
Note that the derived table requires an alias