Multiply by number of days in a month - sql

I've had a decent search on here but can't seem to find what I'm looking for, I think I'm using an incorrect syntax for GETDATE
I'm trying to use a formula that we use as a company to work within my code. That is;
The Price of something / Days in year * days in the month
I'm trying to use the following but to no avail -
[Rate] = Price/'365'*month([Period])))
'Period' is the column name which has the date of the month in the format '2018-04-01' for example
This is based on an example a colleague has shown me but I can't get it to work as I think I'm writing it totally wrong
Apologies for the simple question, I'm brand new to SQL code (well only started in April) so some simple things till are oblivious to me!
Any help here would be really appreciated
Cheers
W

I think you want something like this (assuming 365 days in a year):
select (price / 365.0) * day(eomonth(period)) as rate
If you want to take leap years into account, then:
select (case when eomonth(day(year(period)), 2, 1)) = 28
then (price / 365.0) * day(eomonth(period))
else (price / 366.0) * day(eomonth(period))
end) as rate

I think your code will be like below
[Rate] = (Price*1.00/365) * datepart(day, period)
below is an example by using getdate()
select rate= (12*1.00/365) * datepart(day, getdate())

Related

Date automatically where clause - SQL

I have on my DB the dates that I can filter like this:
select *
where
a.y=2021 and a.m=2 and a.d=7
However if I run this query tomorrow I'll have to go there and change manually.
Is there a way to do this automatically as in if I run the query tomorrow I'll get d=8 and the day after d=9 and so on?
I tried to use get date but I get the following error:
SQL Error [6]: Query failed (#20210207_153809_06316_2g4as): line 2:7: Function 'getdate' not registered
I also don't know if that is the right solution. Does anybody know how to fix that?
you can use NOW to get the current date, and use YEAR , MONTH , DAY to get parts of the date
SELECT *
FROM [TABLE]
WHERE a.y=YEAR(NOW()) and a.m=MONTH(NOW()) and a.d=DAY(NOW())
The best solution is to have a date column in your data. Then you can just use:
where datecol = current_date
Or whatever your particular database uses for the current date.
Absent that, you have to split the current date into parts. In Standard SQL, this looks like:
where y = extract(year from current_date) and
m = extract(month from current_date) and
d = extract(day from current_date)
That said, date functions notoriously vary among databases, so the exact syntax depends on your database.
For instance, a common way to write this in SQL Server would be:
where y = year(getdate()) and
m = month(getdate()) and
d = day(getdate())

Unable to divide to counts of two separate lists in SQL, keeps returning 1

I have one list of events. One event name is creating an account and another is creating an account with Facebook. I am trying to see what percentage of accounts created use Facebook.
The code below will give me an accurate count of the number of facebook accounts and total accounts, but when I try to divide the two numbers it just gives me the number 1.
I am very new to SQL, and have spent hours trying to figure out why it is doing that to no avail.
with
fb_act as (
select *
from raw_event
where name = 'onboard_fb_success'
and event_ts::date >= current_date - 30
),
total_act as (
select *
from raw_event
where name ='create_account'
and event_ts::date >= current_date - 30
)
select count(fb_act)/count(total_act), total_act.event_ts::date as day
from total_act, fb_act
group by day
order by day
I expect the output to be about ~.3, but the actual output is always exactly 1.
Conditional aggregation is a much simpler way to write the query. You appear to be using Postgres, so something like this:
select re.event_ts::date as day,
(sum( (name = 'onboard_fb_success' and event_ts::date >= current_date - 30):: int) /
sum( name = 'create_account' and event_ts::date >= current_date - 30)::int)
) as ratio
from raw_event re
group by re.event_ts::date
order by day;

PHP SQL Select between 4 columns

I´m looking for a solution, where I can select the entries between 2 dates. My table is like this
ID | YEAR | MONTH | ....
Now i want to SELECT all entries between
MONTH 9 | YEAR 2015
MONTH 1 | YEAR 2016
I don´t get any entries, because the 2nd month is lower than the 1st month. Here is my query:
SELECT *
FROM table
WHERE YEAR >= '$year'
AND MONTH >= '$month'
AND YEAR <= '$year2'
AND MONTH <= '$month2'
I can´t change the columns of the table, because a csv import is like this. Can anyone help me on this?
The years aren't disconnected from the months, so you can't test them separately.
Try something like
$date1 = $year*100+$month; // will be 201509
$date2 = $year2*100+$month2; // will be 201602
...
SELECT * FROM table WHERE (YEAR*100)+MONTH >= '$date1' AND (YEAR*100)+MONTH <= '$date2'
Make sure you protect against SQL injection though.
SELECT
*
FROM
`my_table`
WHERE
((`YEAR` * 12) + `MONTH`) >= (($year * 12) + $month)
AND ((`YEAR` * 12) + `MONTH`) <= (($year2 * 12) + $month2)
Since they aren't date fields, you need to convert to numbers that can be compared against. Multiplying the year by 12 and adding the month will give you a unique number specific to that month of the year. Then you can compare on that.
There are a couple of good answers, but assuming taht you don't/can't change the date's format something you can do is
WHERE ((YEAR>'$year') OR
(YEAR=='$year' AND MONTH>='$month')
AND ((YEAR<'$year2') OR
(YEAR=='$year2' AND MONTH<='$month2')
I would suggest the workarounds though (like alphabetically comparing in YYYYMM[DD] format).
You need to pad the month to make sure it starts with a zero. Otherwise 20162 will be lower than 201512, for example.
$date1 = $year . str_pad($month, 2, "0", STR_PAD_LEFT);
$date2 = $year2 . str_pad($month2, 2, "0", STR_PAD_LEFT);
"SELECT * FROM dates WHERE concat(`year`, LPAD(`month`, 2, '0')) >= '$date1' AND concat(`year`, LPAD(`month`, 2, '0')) <= '$date2'"
Though there are a lot of ways to solve this problem, but the best way is to convert these values into a proper date type in mysql query using str_to_date it is PHP's equivalent of strtotime, your new query should look like this
SELECT
d.*
from
dates as d
where
STR_TO_DATE( concat('1,',d.month,',',d.year) ,'%d,%m,%Y') > STR_TO_DATE('1,5,2015','%d,%m,%Y')
and
STR_TO_DATE( concat('1,',d.month,',',d.year) ,'%d,%m,%Y') < STR_TO_DATE('1,4,2016','%d,%m,%Y')
Using this technique you can easily compare dates and do much more and not worry about other complexities of calendars.
Source: MySQL date and time functions

using datepart() with the group by command

I am beating my head against something that is, I'm sure, very obvious -
I have a bit of SQL code designed to sum the total selling price of each invoice in my store and then organize it by Month.
select SUM(totalsellingprice) from dbo.tblServiceOrders
where datepart(MONTH,dbo.tblServiceOrders.datereceived) =12
As far as I understand it, that should return the sum of all the totatlsellingprice from month 12 (December). Currently, this query returns
135998.92
However, if I then try to put that into a group by to get it to spit it out for all months, the number changes.
select SUM(totalsellingprice) from dbo.tblServiceOrders
group by datepart(MONTH,dbo.tblServiceOrders.datereceived)
And I get this table -
1 - 110567.70
2 - 60059.59
3 - 135998.92
4 - 63089.22
5 - 102287.01
6 - 71088.68
7 - 149102.10
8 - 67722.65
9 - 67122.45
10 - 64234.82
11 - 7542.05
12 - 130461.10
There are 12 rows, which sounds good to me (12 months in a year) but the last row is 130461.
How is it possible that row 12 from the second search does not equal what I did in the first search? I feel like I'm missing something obvious but I can't for the life of me figure out what.
Any and all help will be much appreciated!
I got it:
Your query is very confusing since it does not include the MONTH column:
If you would have done that, you would have realized your query is not ordered by MONTH and so, the MONTH 12 is returned as the 3rd row of your query.
;)
select SUM(totalsellingprice) from dbo.tblServiceOrders
group by datepart(MONTH,dbo.tblServiceOrders.datereceived)
order by datepart(MONTH,dbo.tblServiceOrders.datereceived)
And please, don't refer to the row index to choose which month is related to which sum. And should be a good idea to also discriminate the year (if you need to).
Run this and see what it does...
select dateadd(month, datediff(month, 0, datereceived), 0),
Sum(totalsellingprice)
from dbo.tblServiceOrders
group by dateadd(month, datediff(month, 0, datereceived), 0)

Plus 2 date in SQL

I really need help on this those function DATEDIFF OR DateAdd , because I have no idea on those things.
Declare #EstDate as Date,
#Shipdate as Date,
#Workingday as Int,
I need to do like this:
#EstDate(Date) = #ShipDate(DATE) - #WorkingDay(int) - 2days
Example: #EstDate(date) = '6/11/2011' - 5days - 2days.
How can I do this formula in SQL ? >_< In PHP its easy, but in SQL 2000 up, I have no ideas.
I think this will do it. Basically this adds a negative number of days to #ShipDate. The negative number of days will equal #WorkingDay + 2.
I really don't know what #WorkingDay is supposed to represent. This example assumes it's just a number that represents something to you.
#EstDate = DateAdd(dd,-(#WorkingDay + 2),#ShipDate)
It would look something like this, given your example:
#EstDate(date) = DateAdd(dd, -(5 days + 2 days), '6/11/2011')