getting sum for each month for several months in a year in sql - sql

I have the following table
image of database in use
i want to get the following kind of results
jan 12500
feb 16500
mar 4500
apr 6500
the query should return a total for each month for desired months.
i know how to do this..
$sql = "SELECT SUM(cost) as january FROM earnings WHERE month= 1 and year= '$2022" ;
to get the sum for a given month but I cant find anything on how to get multiple months at once.
am still new to this

SELECT
SUM(cost) as cost,
month
FROM earnings
WHERE year = :year
GROUP BY month
Sum all entries of cost, per month (GROUP BY) found in year (:year)
Each ROW will have a column cost and month.
If you want to "further" filter the months you can apply another AND clause
AND (month >= 1 OR month <= 6) for January to June
Useful Source:
https://www.mysqltutorial.org/mysql-group-by.aspx

Related

YTD(Year to date) Calender Flag in qlikview

ordertype actual actual YTD
A 900 1500
B 500 2000
C 200 2200
D 300 2500
Actual column should calculate value from (present date of month minus start date).
Actual YTD should calculate based on present date minus start date of year
Here start date month/year should be april 1 (Financial Year)
In your script use InYearToDate and InMonthToDate
use-case example:
Load distinct
Date,
if(InYearToDate(Date,today(),0,4),1,0) as YTD, // the "4" mean that The year start at the 4th month,
if(InMonthToDate(Date,today(),0),1,0) as MTD
resident DataTable
Now in your Calendar table you the YTD and MTD fields and you can use them like this:
sum({<YTD={1}>} Actual)
for more information about these functions visit here

SQLite - Determine average sales made for each day of week

I am trying to produce a query in SQLite where I can determine the average sales made each weekday in the year.
As an example, I'd say like to say
"The average sales for Monday are $400.50 in 2017"
I have a sales table - each row represents a sale you made. You can have multiple sales for the same day. Columns that would be of interest here:
Id, SalesTotal, DayCreated, MonthCreated, YearCreated, CreationDate, PeriodOfTheDay
Day/Month/Year are integers that represent the day/month/year of the week. DateCreated is a unix timestamp that represents the date/time it was created too (and is obviously equal to day/month/year).
PeriodOfTheDay is 0, or 1 (day, or night). You can have multiple records for a given day (typically you can have at most 2 but some people like to add all of their sales in individually, so you could have 5 or more for a day).
Where I am stuck
Because you can have two records on the same day (i.e. a day sales, and a night sales, or multiple of each) I can't just group by day of the week (i.e. group all records by Saturday).
This is because the number of sales you made does not equal the number of days you worked (i.e. I could have worked 10 saturdays, but had 30 sales, so grouping by 'saturday' would produce 30 sales since 30 records exist for saturday (some just happen to share the same day)
Furthermore, if I group by daycreated,monthcreated,yearcreated it works in the sense it produces x rows (where x is the number of days you worked) however that now means I need to return this resultset to the back end and do a row count. I'd rather do this in the query so I can take the sales and divide it by the number of days you worked.
Would anyone be able to assist?
Thanks!
UPDATE
I think I got it - I would love someone to tell me if I'm right:
SELECT COUNT(DISTINCT CAST(( julianday((datetime(CreationDate / 1000, 'unixepoch', 'localtime'))) ) / 7 AS INT))
FROM Sales
WHERE strftime('%w', datetime(CreationDate / 1000, 'unixepoch'), 'localtime') = '6'
AND YearCreated = 2017
This would produce the number for saturday, and then I'd just put this in as an inner query, dividing the sale total by this number of days.
Buddy,
You can group your query by getting the day of week and week number of day created or creation date.
In MSSQL
DATEPART(WEEK,'2017-08-14') // Will give you week 33
DATEPART(WEEKDAY,'2017-08-14') // Will give you day 2
In MYSQL
WEEK('2017-08-14') // Will give you week 33
DAYOFWEEK('2017-08-14') // Will give you day 2
See this figures..
Day of Week
1-Sunday, 2- Monday, 3-Tuesday, 4-Wednesday, 5-Thursday, 6-Saturday
Week Number
1 - 53 Weeks in a year
This will be the key so that you will have a separate Saturday's in every month.
Hope this can help in building your query.

Qlikview: Past Year data calculations

I have a scenario.
In the sample table below, I need to show the sales by year…
And for each year, I need to show the last yr and last 2nd year sales for that year.
For example in 2014,
Current Year = 2014 Sales
Last Year = 2013 Sales
Current Year = 2013 Sales
Last Year = 2012 Sales
|----------2013------------|---------2014-------------|
| Last Year | Current Year | Last Year | Current Year |
Ive tried but when i nest them under a year dimension.. the calculations are not working.. is there a way around this, to come up with this kind of report format? our user is very particular in having such format..
many thanks for the help.
I'd simply hardcode all rows, and skip the year dimension:
Current Year
Sum({< Date = {">=$(=YearStart(min(Date),0"}*{">=$(=Addyears(max(Date),0)"} >} SalesAmount)
Last Year:
Sum({< Date = {">=$(=YearStart(min(Date),-1"}*{">=$(=Addyears(max(Date),-1)"} >} SalesAmount)
-2 Year:
Sum({< Date = {">=$(=YearStart(min(Date),-2"}*{">=$(=Addyears(max(Date),-2)"} >} SalesAmount)
I think this could be achieved using a pivot table. Here's an example.
You can solve this problem at the script side while loading data. So that you can compare year to date data with previous year with until corresponding month.
Transaction_Table:
LOAD date,productID,amount
FROM data.qvd;
concatenate
Load AddYears(date,1) as date,productID,amount_1
from data.qvd where date<=AddYears($(=max(date)),-1);
Data_Table:
load distinct
date,
month(date) as Month,
year(date) as Year
resident Transaction_Table;
There will be two coloumns "amount" is current date's data and "amount_1" is previous year's same day data.
Create pivot chart put year to top and product to left and create two expressions. One for calculation of amount_1: previous term and one for amount: current term
You can name expressions:
previous year label: =year-1
current year label: =year

Optimize query for for cumulative result

I have this query to find out item count for every month of year. But I am looking for a optimized query for cumulative result
SELECT
COUNT(ITM.ID) AS ItemCount,
Month(ITM.ItemProcureDate),
Year(ITM.ItemProcureDate)
FROM
Rpt_Item ITM
WHERE
ITM.ItemProcureDate IS NOT NULL
AND
ITM.ItemStatusID = 2 -- Item sold, Item Rejected
AND
ITM.ItemProcureDate >= CONVERT(DATETIME,'02/01/2014',1) --#Beg_Date
AND
ITM.ItemProcureDate <= CONVERT(DATETIME,'04/12/2014',1) --#End_Date
GROUP BY
Month(ITM.ItemProcureDate),
Year(ITM.ItemProcureDate)
Query result should be like this:
Item sold In month 2
Item Sold Till Month 2
Item Rejected 1
Item Rejected Till Month 1
Year 2014
Month Feb
Last Date of Month 02/28/2014
-----------------------------------------------
Item sold In month 2
Item Sold Till Month 4
Item Rejected 1
Item Rejected Till Month 2
Year 2014
Month March
LastDate of Month 03/31/2014
-----------------------------------------------
Item sold In month 2
Item Sold Till Month 6
Item Rejected 1
Item Rejected Till Month 3
Year 2014
Month April
Last Date of Month 04/30/2014
I have to find out Item_Sold, Item_Rejected, Item_Added for last three months where every next month it should be cumulative of all previous months values of Item_Sold, Item_Rejected, Item_Added
In SQL Server 2008, you can do this using a correlated subquery or using a non-equijoin. SQL Server 2012 supports a cumulative sum function. Here is a way to do it with a correlated subquery:
with ym as (
SELECT COUNT(ITM.ID) AS ItemCount,
Month(ITM.ItemProcureDate) as mon, Year(ITM.ItemProcureDate) as yr,
Month(ITM.ItemProcureDate) + 100*Year(ITM.ItemProcureDate) as yyyymm
FROM Rpt_Item ITM
WHERE ITM.ItemProcureDate IS NOT NULL AND
ITM.ItemStatusID = 2 AND
ITM.ItemProcureDate >= CONVERT(DATETIME,'02/01/2014',1) AND
ITM.ItemProcureDate <= CONVERT(DATETIME,'04/12/2014',1)
GROUP BY Month(ITM.ItemProcureDate), Year(ITM.ItemProcureDate)
)
select ym.*,
(select sum(ItemCount)
from ym ym2
where ym.yyyymm <= ym.yyyy.mm
) as cumsum
from ym;
Note that this puts the year-month into a YYYYMM format. This is just a convenience so the comparison on the time period uses only one column.
Also, if the ITM table is really big or is a view, then this might not perform as well as one would like. If performance is an issue, use a temporary table instead of a CTE. (SQL Server tends not to materialize CTEs so it is likely to run the code twice.)

Determine monthly values of timestamped records

I have a SQL table with the following schema:
fruit_id INT
price FLOAT
date DATETIME
This table contains many records where the price of a given fruit is recorded at a given time. There may be multiple records in a single day, there may be
I would like to be able to fetch a list of prices for a single fruit over the last 12 months inclusive of the current month. So given a fruit_id of 2 and datetime of now(), what would the price values be for December, January, February, ... October, November?
Given the above requirements, what strategy would you use to get this data? Pure sql, fetch all prices and process in code?
Thanks for you time.
Are you talking about min price, max price, average price, or something else?
Here's a quick query to get you started, which includes min, max, and average price for each month for fruit_id 2:
select left(date,7) as the_month, min(price),max(price),avg(price)
from fruit_price
where fruit_id = 2
and date >= concat(left(date_sub(curdate(), interval 11 month),7),'-01')
group by the_month;
If I understand it correctly from -
I would like to be able to fetch a list of prices for a single fruit over the last 12 months inclusive of the current month. So given a fruit_id of 2 and datetime of now(), what would the price values be for December, January, February, ... October, November?
You want the total price for every month for a single year based on the date and fruit_if you pass in.
So,this won't give all months of an year but all months which had a price for year..in case you want all months..you would need to create a dimdate table which will have all the dates...and then join with it..
declare #passeddate=Now() --date to be calculated
declare #fruit_id=2 --fruit id to be calculated
Select
fruit_id as FruitId,
Sum(price) as MonthPrice,
Month(date) as FruitMonth
from SQL_Table
group by FruitMonth,FruitId
where fruit_id=#fruit_id and
Year(date)=Year(#passeddate)
select month(date) as "Month", distinct(price) as "Unique Price" where fruit_id = 2 group by month(date);
I'd try to state as much as possible in SQL that does not require unindexed access to data because it's usually fast(er) than processing it with the application.