Ms-Access SQL Query - sql

I need some guidance on how to write a query in Ms-Access which will pull all the records based on the PublishedDate but with-in the expiry date. For instance, my table carries 3 columns EventTitle, PublishDate, ExpiryDate with values Title1, 2/22/2012, 3/28/2012.
Now the 1st record will only appear on 22-Feb-2012 until 28-Mar-2012. The query which I used drops the record once the current date changes from 22-Feb to 23-Feb.
I tried using the below script
SELECT top 1 Title, ExpiryDate
FROM Table1
WHERE (((PublishDate)=Date()
Or (PublishDate)<=[ExpiryDate])
AND ((ExpiryDate)>=Date()))
ORDER BY ExpiryDate ASC

Sounds like you want this:
SELECT top 1 Title, ExpiryDate
FROM Table1
WHERE PublishDate<=Date()
AND ExpiryDate>=Date()
ORDER BY ExpiryDate ASC

Related

How to Select latest record in table of Azure SQL?

I have Azure SQL database. There are 100 rows in table.
I have columns CustomerName, SalesAmount, SalesTime in CustomerSales table.
'Nissan','20000','2021-11-19 17:00:27.9866667'
'Nissan','25000','2021-11-02 17:00:27.9866667'
'Tesla' ,'60000','2021-11-01 17:00:27.9866667'
...
I would like make select query which returns single row of latest like
'Nissan','20000','2021-11-19 17:00:27.9866667'
How?
Order the rows in descending order by sales time, and then get first returned row only.
For example:
select top 1 *
from t
order by SalesTime DESC

SQL server select max two dates from a table

I would like to know how if it is possible to select the two most recent dates from a column in a table. Please see the simple example below. I know to get the max date I can use the max function. I'm also aware that I could then do another max statement with a where condition that states it must be less than the first date returned from my first max query. I was wondering though if there was a way of doing this in one query?
Name DateAdded
ABC 2014-04-20
ABC 2014-04-20
ABC 2014-03-01
ABC 2014-03-01
ABC 2014-02-25
ABC 2014-05-22
ABC 2014-04-01
The two dates that should be returned are the two most recent, i.e. 2014-05-22 & 2014-04-20.
EDIT
Sorry I should have mentioned yes I want two distnict dates. The table is large and the dates are not sorted. I think sorting the table could be quite slow.
SELECT distinct top 2 Dateadded
FROM table
ORDER BY Dateadded desc
select top(2) DateAdded
from table
order by DateAdded DESC
Try This :
select distinct top(2) format(Dateadded ,'yyyy-MM-dd') as Dateadded
from TableName
order by Dateadded DESC

Query to Get the last inserted row from a dynamic table grouping by one field

How can we write the query for getting a set of rows where it was last updated grouped by a field name . Example
no - siteid - status - created_at
the 'no' number increases continuously as its the status report provided from another source. As in , Insertion happens 24/7 at some interval. But i want to check the status of 10 sites at the second i run the query .
There are only 10 sites . and i want to generate the report of the status of these 10
as in the last inserted query will give us the current status of the site.
I tried this
SELECT created_at,siteid FROM [TOC].[dbo].[frame1] GROUP BY siteid ORDER BY created_at DESC
But no luck
I'm not actually sure what you want, can you give example input and output data?
For now here is something that might be useful to you...
WITH
sequenced_data AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY site_id ORDER BY created_at DESC) AS sequence_id,
*
FROM
[TOC].[dbo].[Frame1]
)
SELECT
*
FROM
sequenced_data
WHERE
sequence_id = 1

Getting the last record in SQL in WHERE condition

i have loanTable that contain two field loan_id and status
loan_id status
==============
1 0
2 9
1 6
5 3
4 5
1 4 <-- How do I select this??
4 6
In this Situation i need to show the last Status of loan_id 1 i.e is status 4. Can please help me in this query.
Since the 'last' row for ID 1 is neither the minimum nor the maximum, you are living in a state of mild confusion. Rows in a table have no order. So, you should be providing another column, possibly the date/time when each row is inserted, to provide the sequencing of the data. Another option could be a separate, automatically incremented column which records the sequence in which the rows are inserted. Then the query can be written.
If the extra column is called status_id, then you could write:
SELECT L1.*
FROM LoanTable AS L1
WHERE L1.Status_ID = (SELECT MAX(Status_ID)
FROM LoanTable AS L2
WHERE L2.Loan_ID = 1);
(The table aliases L1 and L2 could be omitted without confusing the DBMS or experienced SQL programmers.)
As it stands, there is no reliable way of knowing which is the last row, so your query is unanswerable.
Does your table happen to have a primary id or a timestamp? If not then what you want is not really possible.
If yes then:
SELECT TOP 1 status
FROM loanTable
WHERE loan_id = 1
ORDER BY primaryId DESC
-- or
-- ORDER BY yourTimestamp DESC
I assume that with "last status" you mean the record that was inserted most recently? AFAIK there is no way to make such a query unless you add timestamp into your table where you store the date and time when the record was added. RDBMS don't keep any internal order of the records.
But if last = last inserted, that's not possible for current schema, until a PK addition:
select top 1 status, loan_id
from loanTable
where loan_id = 1
order by id desc -- PK
Use a data reader. When it exits the while loop it will be on the last row. As the other posters stated unless you put a sort on the query, the row order could change. Even if there is a clustered index on the table it might not return the rows in that order (without a sort on the clustered index).
SqlDataReader rdr = SQLcmd.ExecuteReader();
while (rdr.Read())
{
}
string lastVal = rdr[0].ToString()
rdr.Close();
You could also use a ROW_NUMBER() but that requires a sort and you cannot use ROW_NUMBER() directly in the Where. But you can fool it by creating a derived table. The rdr solution above is faster.
In oracle database this is very simple.
select * from (select * from loanTable order by rownum desc) where rownum=1
Hi if this has not been solved yet.
To get the last record for any field from a table the easiest way would be to add an ID to each record say pID. Also say that in your table you would like to hhet the last record for each 'Name', run the simple query
SELECT Name, MAX(pID) as LastID
INTO [TableName]
FROM [YourTableName]
GROUP BY [Name]/[Any other field you would like your last records to appear by]
You should now have a table containing the Names in one column and the last available ID for that Name.
Now you can use a join to get the other details from your primary table, say this is some price or date then run the following:
SELECT a.*,b.Price/b.date/b.[Whatever other field you want]
FROM [TableName] a LEFT JOIN [YourTableName]
ON a.Name = b.Name and a.LastID = b.pID
This should then give you the last records for each Name, for the first record run the same queries as above just replace the Max by Min above.
This should be easy to follow and should run quicker as well
If you don't have any identifying columns you could use to get the insert order. You can always do it like this. But it's hacky, and not very pretty.
select
t.row1,
t.row2,
ROW_NUMBER() OVER (ORDER BY t.[count]) AS rownum from (
select
tab.row1,
tab.row2,
1 as [count]
from table tab) t
So basically you get the 'natural order' if you can call it that, and add some column with all the same data. This can be used to sort by the 'natural order', giving you an opportunity to place a row number column on the next query.
Personally, if the system you are using hasn't got a time stamp/identity column, and the current users are using the 'natural order', I would quickly add a column and use this query to create some sort of time stamp/incremental key. Rather than risking having some automation mechanism change the 'natural order', breaking the data needed.
I think this code may help you:
WITH cte_Loans
AS
(
SELECT LoanID
,[Status]
,ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS RN
FROM LoanTable
)
SELECT LoanID
,[Status]
FROM LoanTable L1
WHERE RN = ( SELECT max(RN)
FROM LoanTable L2
WHERE L2.LoanID = L1.LoanID)

Converting Rows to Columns in SQL SERVER 2008

In SQL Server 2008,
I have a table for tracking the status history of actions (STATUS_HISTORY) that has three columns ([ACTION_ID],[STATUS],[STATUS_DATE]).
Each ACTION_ID can have a variable number of statuses and status dates.
I need to convert these rows into columns that preferably look something like this:
[ACTION_ID], [STATUS_1], [STATUS_2], [STATUS_3], [DATE_1], [DATE_2], [DATE_3]
Where the total number of status columns and date columns is unknown, and - of course - DATE_1 correlates to STATUS_1, etc. And I'd like for the status to be in chronological order (STATUS_1 has the earliest date, etc.)
My reason for doing this is so I can put the 10 most recent Statuses on a report in an Access ADP, along with other information for each action. Using a subreport with each status in a new row would cause the report to be far too large.
Is there a way to do this using PIVOT? I don't want to use the date or the status as a column heading.
Is it possible at all?
I have no idea where to even begin. It's making my head hurt.
Let us suppose for brevity that you only want 3 most recent statuses for each action_id (like in your example).
Then this query using CTE should do the job:
WITH rownrs AS
(
SELECT
action_id
,status
,status_date
,ROW_NUMBER() OVER (PARTITION BY action_id ORDER BY status_date DESC) AS rownr
FROM
status_history
)
SELECT
s1.action_id AS action_id
,s1.status AS status_1
,s2.status AS status_2
,s3.status AS status_3
,s1.status_date AS date_1
,s2.status_date AS date_2
,s3.status_date AS date_3
FROM
(SELECT * FROM rownrs WHERE rownr=1) AS s1
LEFT JOIN
(SELECT * FROM rownrs WHERE rownr=2) AS s2
ON s1.action_id = s2.action_id
LEFT JOIN
(SELECT * FROM rownrs WHERE rownr=3) AS s3
ON s1.action_id = s3.action_id
NULL values will appear in the rows where the action_id has less then 3 status-es.
I haven't had to do it with two columns, but a PIVOT sounds like what you should try. I've done this in the past with dates in a result set where I needed the date in each row be turned into the columns at the top.
http://msdn.microsoft.com/en-us/library/ms177410.aspx
I sympathize with the headache from trying to design and visualize it, but the best thing to do is try getting it working with one of the columns and then go from there. It helps once you start playing with it.