I want to retrieve those records which have Data <= paramdate and also those records which have Date = '1753/01/01'
Thanks
you could use DATEDIFF
DATEDIFF will return different time, day, month, pr year, based what you want to compare.
Example :
`DATEDIFF (DAY, '01/01/2017', '02/01/2017')`
This will return 1, as the comparation is the day.
Note : datediff also could return negative value, as the position which is higher. Example :
'DATEDIFF (DAY, '02/01/2017', '01/01/2017')'
will return -1
When you want to get the data that the date and the format are specified , you could use CONVERT to convert it to your formatted date and compare it like usual
Example :
WHERE CONVERT(VARCHAR, '2017/01/01', 103) = '01/01/2017'
Related
I got the following SQLite database:
What I'm trying to do is: sum all values based on quantidade grouped by Month/Year (e.g.: 2022/08)
The result I'm expecting grouped by year/month:
My SQL code:
SELECT
data, SUM(quantidade) AS sum
FROM stock_tracking_Negociacao
WHERE mercado = 'Futuro'
GROUP BY strftime('%Y', data), strftime('%m', data)
Any help?
We can use SUBSTR() here to isolate the month and year, then aggregate:
SELECT SUBSTR(data, 4, 7) AS ym, SUM(quantidade) AS sum
FROM stock_tracking_Negociacao
WHERE mercado = 'Futuro'
GROUP BY 1;
Note that SQLite does not have a formal date type, but rather stores dates as strings.
For SQLite the only valid text-based date format is YYYY-mm-dd.
When you use any other format with date functions like strftime() the result is null and this is the main reason that your code does not work.
Since you mention that in the database the dates have the format YYYY/mm/dd you can update to the correct format:
UPDATE stock_tracking_Negociacao
SET data = REPLACE(data, '/', '-');
and then your query should be:
SELECT strftime('%Y-%m', data) AS year_month,
SUM(quantidade) AS sum
FROM stock_tracking_Negociacao
WHERE mercado = 'Futuro'
GROUP BY year_month;
I have a table which has a column 'performance month'. The data type of this column is nvarchar(255) and the values are starting from '202001' to '202012'. How can I select last 5 month data from this table?
The simplest way is:
select convert(date, performance_month + '01')
The standard string representation for dates is YYYYMMDD.
For data from the last five months, you can simply use:
performance_month >= format(dateadd(month, -5, getdate()), 'yyyyMM')
That is, don't convert the string to a date. Convert the date to a string -- this helps the optimizer because it can "see" performance_month without the cloud of function calls.
I want to run a query monthly to look for records from the previous month. The where clause will be greater or equal to the 1st day of the month and less or equal to the last day. The difficultly I am having is the dates are stored as numbers in a column with a numeric data type. The format being used is yyyymmdd. We are currently manually changing the where clause, so e.g. show me any records with dates >=20201001 to <=20201031, but we need to automate this process. I have tried a few ways to try and solve this but need some guidance.
So far I've tried:
select concat( CONCAT(cast((Year(DATEADD(month, -1, getdate()))) as numeric),cast((Month(DATEADD(month, -1, getdate()))) as numeric)),'01')
Returns error message operand data type numeric is invalid for concat operator. Works in separate query window returning format yyyymmdd.
SELECT DATEADD(mm, DATEDIFF(mm, 0, (DATEADD(month, -1, getdate()))), 0)
Returns error message arithmetic overflow error converting expression to data type date time. Works partly in separate query window but returns yyyy-mm-dd hh:mi:ss:ms
Any help would be greatly appreciated.
Thanks
The real solution is fix the design; don't store dates in a datatype other than a date and time data type.
What you can do, however, is convert the value of GETDATE() to a numerical value of the same format:
SELECT ...
FROM ...
WHERE NumericalDate >= CONVERT(varchar(8),DATEADD(DAY, 1, EOMONTH(GETDATE(),-1)),112)
AND NumericalDate < CONVERT(varchar(8),DATEADD(DAY, 1, EOMONTH(GETDATE())),112)
For today, this would return rows where NumericalDate is in November 2020 (specifically on or after 20201101 and before but not on 20201201).
Note, I don't "bother" to CAST/CONVERT the varchar to a Numerical data type, as it'll be implicit cast due to data type precedence.
You can use artihmetics like so:
where dates >= year(getdate()) * 10000 + month(getdate()) * 100 + 1
and dates < year(dateadd(month, 1, getdate())) * 10000 + month(dateadd(month, 1, getdate())) * 100 + 1
Compare the month and forget the days.
BETWEEN 20201000 and 20201099 finds the same rows as your example >=20201001 to <=20201031
That means that you do not have to figure out how many days are in the month.
How do I get the first day of the first month of previous year in yyyy-mm-dd format? ie. 2019-01-01.
This is the code I have tried:
SELECT DATEADD(yy,-1,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0))
You can use DATEFROMPARTS() function in SQL Server for creating date from given year, month and date in integer as shown below. To get the previous year you can use Year() function and subtract 1 from that. First date and month is always 1 so it has been hard-coded here.
declare #IntYear int = Year(Getdate()) - 1 --Previous Year
Select datefromparts(#Intyear, 1, 1)
The output in SSMS is as shown below.
To get the output in the different format you can follow this link.
You seem to be looking to generate a string, not a date. Consider using date functions and string concatenation: you just need to substract 1 year from the current date, and then append '-01-01'
concat_ws('-', year(getdate()) - 1, '01', '01')
Demo on DB Fiddle
You basically have it. You just need the FORMAT function.
SELECT FORMAT (DATEADD(yy,-1,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0)), 'yyyy-MM-dd') as date
I have 4 CTE's in this table and the third one contains a DATETIME converted to VARCHAR (with format based on the requirement) as startDate in DD/MM/YYYY format. The last cte does calculations based on the data generated and one of the columns needs to store YYYYMM date based on startDate.
The problem it's getting the year and the month from this converted DATETIME, using convert() it shows this:
IDPER
-------
01/01/ --DD/MM/
These 2 show YYYYMM correctly when startDate isn't converted:
Select *, left(convert(nvarchar(6),new_ini,112),6) as IDPER from table
Select *, convert(nvarchar(6),new_ini,112) as IDPER from table
How could I get YYYYMM format having startDate converted? Or what could be a more smart approach to the requirement
If you have a string in the format DD/MM/YYYY and you want YYYYMM, then use string operations:
select right(new_ini, 4) + substring(new_ini, 4, 2)
You should be storing date values as dates or a related type, not as string. But given that you have already stored this as a string, string operations can do what you need.
My way would be slightly different
SELECT CONVERT(NVARCHAR(6), CONVERT(DATE, new_ini, 103), 112);
Here, I first converted it to date and then formatted to YYYYMMDD and taken 6 chars only
declare #date DATE = GETDATE();
select REPLACE(LEFT(CONVERT(DATE,#date,112),8),'-','') -- 1st approach
select FORMAT(#date,'yyyyMM') --2nd approach