SQL Picking Top Date out of the Date Field - sql

So I have a table with a date column. I want to be able to group these dates by Item field of some type. For example I might have a column called Item and within the Item field there may be 500 entries. Item 12345 might have 5 entires, each with a price. I want to be able to pull out all of the Items, grouped by the newest date.
031126-2M1 8/10/2011 12:00:00 AM 7.8678
031126-2M1 7/22/2011 12:00:00 AM 9.5620
031126-2M1 7/15/2011 12:00:00 AM 8.8090
In this example, I want to show the item with the closest date, 7/15/2011 so I can use that Price of 8.8090. The list would then show the other items, some may have one entry, others might have many, but I want to show all of them with the closets date. Need Help!
Thanks

A MS SQL Server version...
WITH
sorted_data AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY item_id ORDER BY item_date DESC) AS row_id,
*
FROM
item_data
WHERE
item_date <= getDate()
)
SELECT * FROM sorted_data WHERE row_id = 1

selct * from table
where This = that
Group by something having This.
order by date desc.
having "THIS" should be in the query itself.
hope this helps..
Cheers

Related

I want NAV price as per (Today date minus 1) date

I have two tables. One is NAV where product daily new price is updated. Second is TDK table where item wise stock is available.
Now I want to get a summery report as per buyer name where all product wise total will come and from table one latest price will come.
I have tried below query...
SELECT dbo.TDK.buyer, dbo.NAV.Product_Name, sum(dbo.TDK.TD_UNITS) as Units, sum(dbo.TDK.TD_AMT) as 'Amount',dbo.NAV.NAValue
FROM dbo.TDK INNER JOIN
dbo.NAV
ON dbo.TDK.Products = dbo.NAV.Product_Name
group by dbo.TDK.buyer, dbo.NAV.Product_Name, dbo.NAV.NAValue
Imnportant: Common columns in both tables...
Table one NAV has column as Products
Table two TDK has column as Product_Name
If I have NAValue 4 records for one product then this query shows 4 lines with same total.
What I need??
I want this query to show only one line with latest NAValue price.
I want display one more line with Units*NAValue (latest) as "Latest Market Value".
Please guide.
What field contains the quote date? I am assuming you have a DATIME field, quoteDate, in dbo.NAV table and my other assumption is that you only store the Date part (i.e. mid-night, time = 00:00:00).
SELECT
t.buyer,
n.Product_Name,
sum(t.TD_UNITS) as Units,
sum(t.TD_AMT) as 'Amount',
n.NAValue
FROM dbo.TDK t
INNER JOIN dbo.NAV n
ON t.Products = n.Product_Name
AND n.quoteDate > getdate()-2
group by t.buyer, n.Product_Name, n.NAValue, n.QuoteDate
GetDate() will give you the current date and time. Subtracting 2 would get it before yesterday but after the day before yesterday.
Also, add n.quoteDate in your select and group by. Even though you don't need it, in case that one day you have a day of bad data with double record in NAV table, one with midnight time and another with 6 PM time.
Your code looks like SQL Server. I think you just want APPLY:
SELECT t.buyer, n.Product_Name, t.TD_UNITS as Units, t.TD_AMT as Amount, n.NAValue
FROM dbo.TDK t CROSS APPLY
(SELECT TOP (1) n.*
FROM dbo.NAV n
WHERE t.Products = n.Product_Name
ORDER BY ?? DESC -- however you define "latest"
) n;

SQL max without group by

I would like to get one row with the maximum date. I cannot use group by as I need to retrieve all data in that row.
I have this:
ID Date Country
1 05/05/2019 US
2 05/06/2019 UK
I want to get this:
ID Date Country
2 05/06/2019 UK
I've tried the below but it didn't work for me
select TOP 1 ID, Date, country
from table
order by Date desc
I don't believe you. Here is a db<>fiddle that shows three different interpretations of the date in your sample data:
as a string
as mm/dd/yyyy
as dd/mm/yyyy
All three of them produce the same result.
I suspect that your actual data is more complicated and you have oversimplified the example for the question. Further, my suspicion is that the date column is stored as a string rather than a date.
As a string, you might have some hidden characters that affect the sorting (such as leading spaces).
If this is the case, fix the data type and your code will work.
This depends on what DB system you are using.
In Microsoft SQL server, you can use row_number() function:
select top 1 *
from facts
order by ROW_NUMBER() over (order by dateKey)
Can you try this?
select Top 1 ID,Date, country from table where date = max(date)
First set the DATE or DATETIME Datatype in your [Date] column
then try this code:
SELECT TOP 1 ID, [Date] , country FROM TableName ORDER BY Date DESC
SELECT ID,Date,Country from TableName Where Date = MAX(Date) AND Rownum <= 1

how to display last 10 numbers in sql

i have a table A with two column (number varchar(600),Date_ varchar(800))
now i have to display last 10 numbers order by Date_.
SELECT top(10) Number,Date FROM A ORDER BY Date_ DESC,
the problem is that for one month its showing result as desired,
but as soon next month start it not showing result as desired
i want the result like this.
10,2/2/2016
22,1/2/2016
10,31/1/2016
20,30/1/2016
30,29/1/2016
23,28/1/2016
20,27/1/2016
11,26/1/2016
18,25/1/2016
62,24/1/2016
56,23/1/2016
54,22/1/2016
44,21/1/2016
i am getting this result for --/1/2016 month but not for --/2/2016.
so kindly help.
Try the below script
SELECT top(10) Number,Date
FROM A
ORDER BY convert(datetime,Date,103) DESC
If you don't want to/can't change the structure of your table, then you need to use Parsing.
SELECT TOP 10 PARSE(Number AS int) AS Number,
PARSE(Date AS datetime2) AS Date
FROM A
ORDER BY Date DESC
You may need to do a PARSE in your ORDER BY as well.
Just a small change to your code should fix this
SELECT top(10) Number,Date FROM A ORDER BY cast(DATE_ as date) DESC.
Typically dates are stored as numbers in Microsoft world, i.e. 1/1/1900 is 1
1/2/1900 is 2
1/31/1900 is 31 and so on...
So changing your varchar to a date (provided there is no junk in the field) should fix this.

SQL find nearest date without going over, or return the oldest record

I have a view in SQL Server with prices of items over time. My users will be passing a date variable and I want to return the closest record without going over, or if no such record exists return the oldest record present. For example, with the data below, if the user passes April for item A it will return the March record and for item B it will return the June record.
I've tried a lot of variations with Union All and Order by but keep getting a variety of errors. Is there a way to write this using a Case Statement?
example:
case when min(Month)>Input Date then min(Month)
else max(Month) where Month <= Input Date?
Sincere apologies for attaching sample dataset as an image, I couldn't get it to format right otherwise.
Sample Dataset
You can use SELECT TOP (1) with order by DATE DESC + Item type + date comparison to get the latest. ORDER BY will order records by date, then you get the latest either this month (if exists) or earlier months.
Here's a rough outline of a query (without more of your table it's hard to be exact):
WITH CTE AS
(
SELECT
ITEM,
PRICE,
MIN(ACTUAL_DATE) OVER (PARTITION BY ITEM ORDER BY ITEM) AS MIN_DATE,
MAX(INPUT_DATE<=ACTUAL_DATE) OVER (PARTITION BY ITEM ORDER BY ITEM,ACTUAL_DATE) AS MATCHED_DATE
FROM TABLE
)
SELECT
CTE.ITEM,
CTE.PRICE,
CASE
WHEN
CTE.MATCHED_DATE IS NOT NULL
THEN
CTE.MATCHED_DATE
ELSE
CTE.MIN_DATE
END AS MOSTLY_MATCHED_DATE
FROM CTE
GROUP BY
CTE.ITEM,
CTE.PRICE
The idea is that in a Common Table Expression, you use the PARTITION BY function to identify the key date for each item, record by record, and then you do a test in aggregate to pull either your matched record or your default record.

SQL statement to find Min Date

I am new to SQL so I am fumbling here a bit. I have the following table:
Entered Generalist Item
12/31/2012 07:26:50 Tom Smith RTW/Updates
12/31/2012 07:30:10 Terrie Bradshaw Posters
12/31/2012 07:38:16 Jen Lopez Client Assistance/Request
12/31/2012 07:48:00 Tom Smith RTW/Updates
12/31/2012 07:50:29 Mike Smith RTW/Updates
12/31/2012 07:55:32 Tom Smith Client Assistance/Request
I am trying to find out when was the last time a rep was assigned an item. So I am looking for the Min value on a column. My query would look at Item "RTW/Updates" when was the earlier time entered between a date range and return Tom Smith. For example the user queries, RTW/Update between 12/31/2012 and 1/1/2013 and the answer would be Tom Smith.
This is what I have so far, but have not been able to figure out the between the dates part:
SELECT MIN(entered), generalist, item
FROM dataTable
That is pretty much it.
I May not understand what you want, but if you want to get one person back based on the minimum date, you need to work out the minimum date, and use that to find that person:
select
*
from
datatable
where
entered =
(
select
min(entered) as MinDate
from
DataTable
where
Item = 'RTW/Updates'
)
and item = 'RTW/Updates'
SQL Fiddle
You could also use a CTE:
; with LowDate as
(select
min(entered) as MinDate
from
DataTable
where
Item = 'RTW/Updates' )
select
*
from
datatable
inner join LowDate
ON entered = LowDate.MinDate
and item = 'RTW/Updates'
More SQL Fiddle!
You are looking for the window functions. Here is an example:
select generalist, item, entered
from (SELECT generalist, item, entered,
row_number() over (partition by item order by entered desc) as seqnum
FROM dataTable
) t
where seqnum = 1;
The function row_number() enumerates the rows for each item (based on the partition by clause) starting with 1. The row with 1 is going to have the most recent date, because of the order by clause.
The outer query just selects the rows where the seqnum = 1 -- which is the most recent record for each item.
I believe this should work (where the # variables are the parameters passed to your procedure)
SELECT MIN(entered), generalist, item
FROM dataTable
WHERE item = #itemParm
AND entered BETWEEN #enteredStart AND #enteredEnd
GROUP BY generalist, item
Use GROUP BY
SELECT MAX(entered) MinDate, generalist, item FROM dataTable
GROUP BY Generalist, Item
Just to add something to the answers (which are correct, essentially) before this one : in order to find the latest date, you'll have to use MAX() instead of MIN().
SELECT MIN(entered) MinDate, generalist, item
FROM dataTable
GROUP BY generalist, item
When you have used an aggregate function in your select statement and you are also selecting other column which are not contained in any aggregate function you have to tell sql server how to aggregate that column by adding a GROUP BY clause and mentioning names of all the column that are in SELECT statement but not contained in any Aggregate function.
to get the latest Date you will need to get the Biggest(Largest in Number Date) and you will need to use MAX() function instead of MIN(), MIN() will return the Oldest (smallest Date) in your column.
SELECT MAX(entered) MinDate, generalist, item
FROM dataTable
GROUP BY generalist, item