Add same day in a year month column - sql

I am trying to add the day 15 in each of the year_month column record.
Here an example of what I want to achieve. This applies to all the year_month record. Basically all the year_month records should contain a 15 after the month
From
year month year_month
-----------------------------
2019 4 2019-04
2019 6 2019-06
To
year month year_month
-----------------------------
2019 4 2019-04-15
2019 6 2019-06-15
Didn't try any code yet as honestly I don't know how to start.

You can use datefromparts() function. It takes year, month and day as arguments and produces a date from it. You can hardcoded day 15.
select datefromparts(year, month, 15)

One more way to do using CAST() and CONCAT()
SELECT CAST(CONCAT([year], '-', [month], '-15') AS DATE)
Example: SELECT CAST(CONCAT(2019, '-', 4, '-15') AS DATE) will result as 2019-04-15

If year_month is a string, then:
update t
set year_month = year_month + '-15';
Once you do this, I would suggest changing the type to a date:
alter table t alter year_month date;
Or, if you just want a date in the table when you select it:
alter table t add year_month_date as (convert(date, year_month + '-15'));
This adds a computed column which is a date to the table. You can then select it and use it in queries as you would any other column.

Related

Using Date to find the inequality for sales than 500

I'm curious as to find the daily average sales for the month of December 1998 not greater than 100 as a where clause. So what I imagine is that since the table consists of the date of sales (sth like 1 december 1998, consisting of different date, months and year), amount due....First I'm going to define a particular month.
DEFINE a = TO_DATE('1-Dec-1998', 'DD-Month-YYYY')
SELECT SUBSTR(Sales_Date, 4,6), (SUM(Amount_Due)/EXTRACT(DAY FROM LAST_DAY(Sales_Date))
FROM ......
WHERE SUM(AMOUNT_DUE)/EXTRACT(DAY FROM LAST_DAY(&a)) < 100
I'm stuck as to extract the sum of amount due in the month of december 1998 for the where clause....
How can I achieve the objective?
To me, it looks like this:
select to_char(sales_date, 'mm.yyyy') month,
avg(amount_due) avg_value
from your_table
where sales_date >= trunc(date '1998-12-01', 'mm')
and sales_date < add_months(trunc(date '1998-12-01', 'mm'), 1)
group by to_char(sales_date, 'mm.yyyy')
having avg(amount_due) < 100;
WHERE clause can be simplified; it shows how to fetch certain period:
trunc to mm returns first day in that month
add_months to the above value (first day in that month) will return first day of the next month
the bottom line: give me all rows whose sales_date is >= first day of this month and < first day of the next month; basically, the whole this month
Finally, the where clause you used should actually be the having clause.
As long as the amount_due column only contains numbers, you can use the sum function.
Below SQL query should be able to satisfy your requirement.
Select SUM(Amount_Due) from table Sales where Sales_Date between '1-12-1998' and '31-12-1998'
OR
Select SUM(Amount_Due) from table Sales where Sales_Date like '%-12-1998'

SQL how to sum quantity monthly for report

I have table like this
PartID Quantity Date
12315 1 2017-01-24
51245 3 2017-01-26
12345 4 2017-02-20
12415 1 2017-02-25
..... .. ...........
I need for the report result like:
Monthly Quantity January: 4
Monthly Quantity February: 5
So in my report - every column should have the name of month and include all quantities (count) for this month. Any help would be appreciated.
I think you are looking for a query like:
select month(Date), sum(Quantity)
from table
group by month(Date)
In MS SQL :
You can use something like this:
DATENAME() function returns a specified part of a given date, as a string value.
To know more about DATENAME(), please visit https://www.w3schools.com/sql/func_sqlserver_datename.asp
CAST() function converts an expression from one data type to another data type.
To know more about CAST(), please visit https://www.w3schools.com/sql/func_sqlserver_cast.asp
SELECT
MONTH(Date) AS MonthNo,
'Monthly Quantity ' + DATENAME(MONTH, date) + ' : ' + CAST(SUM(Quantity) AS nvarchar(10)) AS Monthwise
FROM parttable
GROUP BY DATENAME(MONTH, date),
MONTH(Date)
ORDER BY MONTH(Date)
So the output will be
Two options you can have :
1) create another column and store name of month in it .
PartID Quantity Date. Month
12315 1 2017-01-24. January
51245 3 2017-01-26. January
12345 4 2017-02-20. February
12415 1 2017-02-25. February
And use below query to get the report as you needed :
Select sum(Quantity) as total_quantity, Month from table group by Month
2) by using inbuilt date and time functions of MySQL.
Select sum(Quantity) as total_quantity, Month(Date) as month from table group by Month(Date)
Which database are you using?
On SQL Server:
SELECT
DATENAME(month, Date) AS 'Month Name', SUM(Quantity)
FROM table
GROUP BY DATENAME(month, Date)

Sum entries of an sqlite query

I have a table similar to this:
| id(INTEGER) | id2(INTEGER) | time(DATETIME) | value(REAL) |
|-------------|--------------|----------------------|-------------|
| 1 | 2000 | 2004-01-01 00:00:00 | 1000 |
which I query with visual basic. Now I want to sum all entries between year 2004 and 2010 so the result looks like this:
2004 11,000
2005 35,000
2006 46,000
cIf I do it inside visual basis it is achieved with few loops but unfortunately this is not very performant.
Is it possible to create a query which yields the result say between two years grouped by years. Or between two months (within one year), grouped by months, days (within one month), hours (within one day), minutes (within one hour)?
EDIT:
Query for year interval:
SELECT STRFTIME('%Y', time) AS year, SUM(value) AS cumsum FROM mytable WHERE year >= STRFTIME('%Y','2005-01-01 00:00:00') AND year <= STRFTIME('%Y','2010-01-01 00:00:00') GROUP BY STRFTIME('%Y', mytable.time) ORDER BY year;
Now need an idea for months, days and hours.
This is an aggregation query, but you need to extract the year from the date:
select strftime('%Y', time) as yr, sum(value)
from table
group by strftime('%Y', time)
order by yr;
Hi Below is the code for both sql and sqlite.we can do group by time instead of using the strftime function again.
SQLITE:
select strftime('%Y',
time)as year , sum(value) value
from attendence group by time
SQL:
select EXTRACT(YEAR FROM time) as year, sum(value) value
from attendence Group by time

SQL Month Year datatypes

Its really frustrating whenever I have to work with date/ datetime datatypes and SQL doesn't provide a good and easy way to work with it.
Currently I have this table RecordsDaily with a column Date with datatype date. I want to convert the Date column to month and take only distinct month values AND then sort according to month. Below is the query.
select distinct(CAST(DATEPART(year,Date) as varchar(10)) + ' ' + datename(MONTH,Date)) Month
from P98.dbo.RecordsDaily
where Date >= '2013/12/1'
order by Month
Obviously since I have made it varchar it doesn't consider it as date datatype and sorts it alphabetically as below.
Month
2013 December
2014 April
2014 February
2014 January
2014 March
2014 May
Any help to make it sort as per calendar.
UPDATE
Please note the output should be with Month and Year
Please try:
select Month from(
select distinct(CAST(DATEPART(year,Date) as varchar(10)) + ' ' + datename(MONTH,Date)) Month
,year(Date) yr, month(Date) mn
from P98.dbo.RecordsDaily
where Date >= '2013/12/1'
)x
order by yr, mn
try this !
select * from table order by cast(('01'+id) as datetime)asc
-- id is your column_name

Return just the last day of each month with SQL

I have a table that contains multiple records for each day of the month, over a number of years. Can someone help me out in writing a query that will only return the last day of each month.
SQL Server (other DBMS will work the same or very similarly):
SELECT
*
FROM
YourTable
WHERE
DateField IN (
SELECT MAX(DateField)
FROM YourTable
GROUP BY MONTH(DateField), YEAR(DateField)
)
An index on DateField is helpful here.
PS: If your DateField contains time values, the above will give you the very last record of every month, not the last day's worth of records. In this case use a method to reduce a datetime to its date value before doing the comparison, for example this one.
The easiest way I could find to identify if a date field in the table is the end of the month, is simply adding one day and checking if that day is 1.
where DAY(DATEADD(day, 1, AsOfDate)) = 1
If you use that as your condition (assuming AsOfDate is the date field you are looking for), then it will only returns records where AsOfDate is the last day of the month.
Use the EOMONTH() function if it's available to you (E.g. SQL Server). It returns the last date in a month given a date.
select distinct
Date
from DateTable
Where Date = EOMONTH(Date)
Or, you can use some date math.
select distinct
Date
from DateTable
where Date = DATEADD(MONTH, DATEDIFF(MONTH, -1, Date)-1, -1)
In SQL Server, this is how I usually get to the last day of the month relative to an arbitrary point in time:
select dateadd(day,-day(dateadd(month,1,current_timestamp)) , dateadd(month,1,current_timestamp) )
In a nutshell:
From your reference point-in-time,
Add 1 month,
Then, from the resulting value, subtract its day-of-the-month in days.
Voila! You've the the last day of the month containing your reference point in time.
Getting the 1st day of the month is simpler:
select dateadd(day,-(day(current_timestamp)-1),current_timestamp)
From your reference point-in-time,
subtract (in days), 1 less than the current day-of-the-month component.
Stripping off/normalizing the extraneous time component is left as an exercise for the reader.
A simple way to get the last day of month is to get the first day of the next month and subtract 1.
This should work on Oracle DB
select distinct last_day(trunc(sysdate - rownum)) dt
from dual
connect by rownum < 430
order by 1
I did the following and it worked out great. I also wanted the Maximum Date for the Current Month. Here is what I my output is. Notice the last date for July which is 24th. I pulled it on 7/24/2017, hence the result
Year Month KPI_Date
2017 4 2017-04-28
2017 5 2017-05-31
2017 6 2017-06-30
2017 7 2017-07-24
SELECT B.Year ,
B.Month ,
MAX(DateField) KPI_Date
FROM Table A
INNER JOIN ( SELECT DISTINCT
YEAR(EOMONTH(DateField)) year ,
MONTH(EOMONTH(DateField)) month
FROM Table
) B ON YEAR(A.DateField) = B.year
AND MONTH(A.DateField) = B.Month
GROUP BY B.Year ,
B.Month
SELECT * FROM YourTableName WHERE anyfilter
AND "DATE" IN (SELECT MAX(NameofDATE_Column) FROM YourTableName WHERE
anyfilter GROUP BY
TO_CHAR(NameofDATE_Column,'MONTH'),TO_CHAR(NameofDATE_Column,'YYYY'));
Note: this answer does apply for Oracle DB
Here's how I just solved this. day_date is the date field, calendar is the table that holds the dates.
SELECT cast(datepart(year, day_date) AS VARCHAR)
+ '-'
+ cast(datepart(month, day_date) AS VARCHAR)
+ '-'
+ cast(max(DATEPART(day, day_date)) AS VARCHAR) 'DATE'
FROM calendar
GROUP BY datepart(year, day_date)
,datepart(month, day_date)
ORDER BY 1