T- SQL compare two date column and find month number - sql

I am new in this business. hope you could help me to sort out below problem with CASE Statement. I need to compare two columns where date values are there but the result will be as like as the picture below.
Thank you
Nayeem

Try something like this...
select
first_date
,second_date
,case
when first_date > second_date
then
substring(datename(month,first_date),1,3) + '-' + substring(datename(year,first_date),3,2)
else
substring(datename(month,second_date),1,3) + '-' + substring(datename(year,second_date),3,2)
end as result
from (
select CONVERT(datetime, '2017-08-25') as first_date ,CONVERT(datetime, '2017-02-02') as second_date
union
select CONVERT(datetime, '2018-01-25') as first_date ,CONVERT(datetime, '2018-12-04') as second_date
union
select CONVERT(datetime, '2019-11-14') as first_date ,CONVERT(datetime, '2019-11-14') as second_date
) x;
;

Assuming your date columns are indeed dates, you seem to be looking for:
select format(coalesce(start_date_1, start_date_2), 'MMM-yy')
from t;

Related

Convert date time format and select distinct in SQL

I need to select the distinct date time from 2 columns.
First convert the date time into new format 'yyyy-mm-dd hh:mm:ss' and select only the distinct value. Such as: convert and take the only 1 time value 12:59:43 among 3 results.
But when i try to add format or convert function into this, it was failed or not showing right results. Any help please? Thank you.
The original code i use below:
SELECT DISTINCT *
FROM
( SELECT TOP 100000000
[Start] AS Station_Start_Date,
[End] AS Station_End_Date
FROM ***
WHERE *** = 1476541 AND [End] IS NOT NULL AND [Start] IS NOT NULL
GROUP BY
[End],
[Start]
ORDER BY [Start] DESC)
try the following:
SELECT DISTINCT convert(varchar(19), t.Station_Start_Date, 120) Station_Start_Date
, convert(varchar(19), t.Station_End_Date, 120) Station_End_Date
FROM #t t
or
SELECT convert(varchar(19), t.Station_Start_Date, 120) Station_Start_Date
, convert(varchar(19), t.Station_End_Date, 120) Station_End_Date
FROM #t t
GROUP BY convert(varchar(19), t.Station_Start_Date, 120), convert(varchar(19), t.Station_End_Date, 120)
Please find the db<>fiddle here.

SQL query to get result for a date range when table got Year and Month fields

I have a table with Year and Month fields. I need to select the rows between two particular dates. How do I set this in the where condition?
You are a bit unclear on what "between" means in this context. I'm pretty sure that datefromparts() can be quite helpful:
select t.*
from t
where #date_start <= datefromparts(year, month, 1) and
#date_end >= datefromparts(year, month, 1);
You might also find eomonth() helpful, if the end of the month is an important date.
You can try with help month(),year() function of date
Here is the example:
select * from t where (t.month=month('2017-01-01') and t.year=year('2017-01-01')) and (t.month=month('2017-05-01') and t.year=year('2017-05-01'));
Below is the link for month() in sql.
https://learn.microsoft.com/en-us/sql/t-sql/functions/month-transact-sql
This might help you in solving your problem.
you can also try something like:
select
d.*
from
(select
t.*,
cast(rtrim(cast([month] as char(2))) + '/1/' + cast ([year] as char(4)) as date) as dt) d
where
dt >= #dateStart and
dt <= #dateEnd
If the year and month values are integers, you can cast them to varchar, then date, and use BETWEEN. An example with declaring startdate and enddate variables:
DECLARE #startdate date = '2015-07-01'
,#enddate date = '2016-07-01'
SELECT *
FROM #myTable
WHERE CAST(CAST(Year as varchar) + '-' + CAST(Month as varchar) + '-01' as date)
BETWEEN #startdate AND #enddate
If they are chars or varchars you need only cast to date and use BETWEEN:
DECLARE #startdate date = '2015-07-01'
,#enddate date = '2016-07-01'
SELECT *
FROM #myTable
WHERE CAST(Year + '-' + Month + '-01' as date)
BETWEEN #startdate AND #enddate
Try with "Between".
Something like this:
SELECT SALES_AMOUNT FROM TABLE WHERE YEAR BETWEEN 2015 AND 2016 AND MONTH BETWEEN 6 AND 8

how to Select getdate () in yyyy/M format

I want to select getdate() in the format yyyy/M. I tried to write a query
SELECT FORMAT(GETDATE(), 'yyyy/M')
but it is throwing an error.
I am a beginner in SQL. How do I get the yyyy/m format if there is only single digit month? E.g. the query should return 2016/1 when there is only one digit month (it should not return 2016/01) and should return 2016/10 when the month has two digits
How about getting the YEAR and MONTH part of the date and just concatenate them:
SELECT
CAST(DATEPART(YEAR, GETDATE()) AS VARCHAR(4)) + '/' +
CAST(DATEPART(MONTH, GETDATE()) AS VARCHAR(2))
Try this:
SELECT FORMAT(GETDATE(),'yyyy/MM')
SELECT FORMAT(CAST('2015-11-15' AS smalldatetime),'yyyy/M'),
FORMAT(CAST('2015-01-15' AS smalldatetime),'yyyy/M')
Gives:
2015/11 | 2015/1
SELECT CONVERT(VARCHAR(7), GETDATE(), 111) AS [YYYY/MM]
OR
SELECT CONVERT(VARCHAR(7), GETDATE(), 111)

Get Hours and Minutes (HH:MM) from date

I want to get only hh:mm from date.
How I can get this?
I have tried this :
CONVERT(VARCHAR(8), getdate(), 108)
Just use the first 5 characters...?
SELECT CONVERT(VARCHAR(5),getdate(),108)
You can easily use Format() function instead of all the casting for sql 2012 and above only
SELECT FORMAT(GETDATE(),'hh:mm')
This is by far the best way to do the required conversion.
Another method using DATEPART built-in function:
SELECT cast(DATEPART(hour, GETDATE()) as varchar) + ':' + cast(DATEPART(minute, GETDATE()) as varchar)
If you want to display 24 hours format use:
SELECT FORMAT(GETDATE(),'HH:mm')
and to display 12 hours format use:
SELECT FORMAT(GETDATE(),'hh:mm')
Following code shows current hour and minutes in 'Hour:Minutes' column for us.
SELECT CONVERT(VARCHAR(5), GETDATE(), 108) +
(CASE WHEN DATEPART(HOUR, GETDATE()) > 12 THEN ' PM'
ELSE ' AM'
END) 'Hour:Minutes'
or
SELECT Format(GETDATE(), 'hh:mm') +
(CASE WHEN DATEPART(HOUR, GETDATE()) > 12 THEN ' PM'
ELSE ' AM'
END) 'Hour:Minutes'
The following works on 2008R2+ to produce 'HH:MM':
select
case
when len(replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','')) = 4
then '0'+ replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','')
else replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','') end as [Time]
You can cast datetime to time
select CAST(GETDATE() as time)
If you want a hh:mm format
select cast(CAST(GETDATE() as time) as varchar(5))
Here is syntax for showing hours and minutes for a field coming out of a SELECT statement. In this example, the SQL field is named "UpdatedOnAt" and is a DateTime. Tested with MS SQL 2014.
SELECT Format(UpdatedOnAt ,'hh:mm') as UpdatedOnAt from MyTable
I like the format that shows the day of the week as a 3-letter abbreviation, and includes the seconds:
SELECT Format(UpdatedOnAt ,'ddd hh:mm:ss') as UpdatedOnAt from MyTable
The "as UpdatedOnAt" suffix is optional. It gives you a column heading equal tot he field you were selecting to begin with.
TO_CHAR(SYSDATE, 'HH')
I used this to get the current hour in apex PL/SQL

How I can select / sort dates by period intervals?

For ex:
If we have in table records like:
25/06/2009
28/12/2009
19/02/2010
16/04/2011
20/05/2012
I want to split/select this dates according to 6 month intervals starting from current date.
result should be like:
0-6 month from now: first record
7-12 month from now: second record
...
It will be much apreciated if you make this simple as I made it very stupid and complicated like:
declare variable like t1=curdate()+6
t2=curdate()+12
...
then selected records to fit between curdate() and t1, then t1 and t2 etc.
Thanks,
r.
CORRECTION: Had it backwards, Need to use Modulus, not integer division - sorry...
If MonthCount is a calculated value which counts the number of months since a specific Dec 31, and mod is modulus division (output the remainder after dividing)
Select [Column list here]
From Table
Group By Case When MonthCount Mod 12 < 6
Then 0 Else 1 End
In SQL Server, for example, you could use the DateDiff Function
Select [Column list here]
From Table
Group By Case When DateDiff(month, myDateColumn, curdate) % 12 < 6
Then 0 Else 1 End
( in SQL Server the percent sign is the modulus operator )
This will group all the record into buckets which each contain six months of data
SELECT (DATEDIFF(MONTH, thedate, GETDATE()) / 6) AS semester,
SUM(receipt)
FROM thetable
GROUP BY semester
ORDER BY semester
the key idea is grouping and ordering by the expression that gives you the "semester".
This question really baffled me, cos I couldn't actually come up with a simple solution for it. Damn.
Best I could manage was an absolute bastardization of the following where you create a Temp Table, insert the "Periods" into it, join back to your original table, and group off that.
Assume your content table has the following
ID int
Date DateTime
Counter int
And you're trying to sum all the counter's in six month periods
DECLARE #min_date datetime
select #min_date = min(date) from test
DECLARE #max_date datetime
select #max_date = max(date) from test
DECLARE #today_a datetime
DECLARE #today_b datetime
set #today_a = getdate()
set #today_b = getdate()
CREATE TABLE #temp (startdate DateTime, enddate DateTime)
WHILE #today_a > #min_date
BEGIN
INSERT INTO #temp (startDate, endDate) VALUES (dateadd(month, -6, #today_a), #today_a)
SET #today_a = dateadd(month, -6, #today_a)
END
WHILE #today_b < #max_date
BEGIN
INSERT INTO #temp (startDate, endDate) VALUES (#today_b, dateadd(month, 6, #today_b))
SET #today_b = dateadd(month, 6, #today_b)
END
SELECT * FROM #temp
SELECT
sum(counter),
'Between ' + Convert(nvarchar(10), startdate, 121) + ' => ' + Convert(nvarchar(10), enddate, 121) as Period
FROM test t
JOIN #Temp ht
ON t.Date between ht.startDate AND ht.EndDate
GROUP BY
'Between ' + Convert(nvarchar(10), startdate, 121) + ' => ' + Convert(nvarchar(10), enddate, 121)
DROP TABLE #temp
I really hope someone can come up with a better solution my brain has obviously melted.
Not quite what you're attempting to accomplish, but you could use the DATEDIFF function to distinguish the ranging of each record:
SELECT t.MonthGroup, SUM(t.Counter) AS TotalCount
FROM (
SELECT Counter, (DATEDIFF(m, GETDATE(), Date) / 6) AS MonthGroup
FROM Table
) t
GROUP BY t.MonthGroup
This would create a sub query with an expression that expresses the date ranging group you want. It would then group the sub-query by this date ranging group and you can then do whatever you want with the results.
Edit: I modified the example based on your example.
If you're using SQL Server:
SELECT *,
(
FLOOR
(
(
DATEDIFF(month, GETDATE(), date_column)
- CASE WHEN DAY(GETDATE()) > DAY(date_column) THEN 1 ELSE 0 END
) / 6.0
) * 6
) AS SixMonthlyInterval
FROM your_table
If you're using MySQL:
SELECT *,
(
FLOOR
(
(
((YEAR(date_column) - YEAR(CURDATE())) * 12)
+ MONTH(date_column) - MONTH(CURDATE())
- CASE WHEN DAY(CURDATE()) > DAY(date_column) THEN 1 ELSE 0 END
) / 6.0
) * 6
) AS SixMonthlyInterval
FROM your_table