SQL Server : get date range and number of days - sql

I have 4 columns (two columns filter) and one column date and one column flag.
For a combination of column 1 and column 2, and the open flag, I want to find the open date, the close date and number of days where it was open.
Here is my example and what I want to find with SQL is with the blue/grey color

You can use DATEDIFF() function as shown below if you have already two dates available as OpenDate and CloseDate in your case.
Select DATEDIFF(DAY, OpenDate, CloseDate) as NumberOfOpenDays from YourTable

This looks a gaps-and-islands problem -- but the islands are already defined by opendt (and perhaps col1 and col2).
So, you can just use row_number():
select row_number() over (partition by col1, col2, opendt order by effectivedt)

Related

SQL : How can I get previous day [duplicate]

This question already has answers here:
Is there a way to access the "previous row" value in a SELECT statement?
(9 answers)
Closed 8 months ago.
How can I get the result in the PreviousDay column that the day should be -1 from the day in efdt column for all rows?
If the efdt date is 2001-04-02 the result in PreviousDay should be 2001-04-01 and DATEDIFF is 334
Image attached with it please refer it.
You can use the SQL Server LEAD window function over the "efdt" field, which will take the following value given two clauses:
PARTITION BY, which indicates the groups to work on
ORDER BY, which decided which value to take according to an order imposed by one (or more) of your fields.
SELECT T.*,
DATEDIFF(DAY, efdt, PreviousDay)
FROM (SELECT T1.*,
LEAD(efdt) OVER(PARTITION BY emcd ORDER BY efdt) AS PreviousDay
FROM psf206 T1) AS T
ORDER BY emcd, efdt
Check the demo here.
Note: if you want one day less for each row, just add -1 after the DATEDIFF operation (demo).

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: select datetime values prior to that date based on it's value

I want to select rows for a field MRD which is declared as date where it is prior for that date only.
So
(case when sum (transPoints) > 4 and MRD is that same date then 4
So if a row has a date of today, I want the case when to be triggered when the transaction points are bigger than 4 against all columns with the same date.
As you can imagine the date field will be different against many rows.
Based on what I can understand from your question, it seems that the GROUP BY clause may be what you're looking for. If your date column is in the correct format then you may have to use something like:
SELECT CAST(DateColumn as DATE)
FROM YourTable
GROUP BY CAST(DateColumn as DATE)

How to group by a date column by month

I have a table with a date column where date is stored in this format:
2012-08-01 16:39:17.601455+0530
How do I group or group_and_count on this column by month?
Your biggest problem is that SQLite won't directly recognize your dates as dates.
CREATE TABLE YOURTABLE (DateColumn date);
INSERT INTO "YOURTABLE" VALUES('2012-01-01');
INSERT INTO "YOURTABLE" VALUES('2012-08-01 16:39:17.601455+0530');
If you try to use strftime() to get the month . . .
sqlite> select strftime('%m', DateColumn) from yourtable;
01
. . . it picks up the month from the first row, but not from the second.
If you can reformat your existing data as valid timestamps (as far a SQLite is concerned), you can use this relatively simple query to group by year and month. (You almost certainly don't want to group by month alone.)
select strftime('%Y-%m', DateColumn) yr_mon, count(*) num_dates
from yourtable
group by yr_mon;
If you can't do that, you'll need to do some string parsing. Here's the simplest expression of this idea.
select substr(DateColumn, 1, 7) yr_mon, count(*) num_dates
from yourtable
group by yr_mon;
But that might not quite work for you. Since you have timezone information, it's sure to change the month for some values. To get a fully general solution, I think you'll need to correct for timezone, extract the year and month, and so on. The simpler approach would be to look hard at this data, declare "I'm not interested in accounting for those edge cases", and use the simpler query immediately above.
It took me a while to find the correct expression using Sequel. What I did was this:
Assuming a table like:
CREATE TABLE acct (date_time datetime, reward integer)
Then you can access the aggregated data as follows:
ds = DS[:acct]
ds.select_group(Sequel.function(:strftime, '%Y-%m', :date_time))
.select_append{sum(:reward)}.each do |row|
p row
end