Sum of totals grouped by month - sql

I've been out of the dev world for a few years so forgive me if this is a pretty basic question but I have an app that logs bookings for holiday accomodation. I want to produce a report detailing how much income per month a user gets.
My query thus far is as so:-
SELECT SUM(int_ToOwner) AS TotalIncome,
DateName(m,dtm_StartDate) AS BookingMonth
FROM tbl_Bookings
WHERE dtm_StartDate > '2021-12-31'
GROUP BY DatePart(m,dtm_StartDate), int_ToOwner, dtm_StartDate
But that produces the result below. I want it to give me a total for each month instead.
TotalIncome
BookingMonth
553.00
January
849.00
January
885.00
February
1236.00
February
1239.00
February
896.00
March
927.00
March
940.00
March
959.00
March
971.00
March
1167.00
April
1255.00
April
1500.00
April
2461.00
April
1131.00
May
1172.00
May
1275.00
May
2647.00
May
1466.00
June
1480.00
June
1496.00
June
1899.00
June
2167.00
June
1881.00
July
4990.00
July
4991.00
July
2134.00
August
4162.00
August
4883.00
August
5329.00
August
1430.00
September
1630.00
October
1130.00
November

You almost have it but you are also grouping by int_ToOwner and you have the dtm_StartDate twice.
Try:
SELECT SUM(int_ToOwner) AS TotalIncome, DateName(m,dtm_StartDate) AS BookingMonth
FROM tbl_Bookings
WHERE dtm_StartDate > '2021-12-31'
GROUP BY DatePart(m,dtm_StartDate)

A little re-format:
SELECT SUM(int_ToOwner) AS TotalIncome
, DateName(m,dtm_StartDate) AS BookingMonth
FROM tbl_Bookings
WHERE dtm_StartDate > '2021-12-31'
GROUP BY DatePart(m,dtm_StartDate)
, int_ToOwner
, dtm_StartDate
Your GROUP BY tells the database to create groups for data with equal values of
DatePart(m,dtm_StartDate)
int_ToOwner
dtm_StartDate
Then SELECT asks for each group the
calculated SUM of int_ToOwner
DateName(m,dtm_StartDate)
You should search your solution in grouping the correct attributes.

Related

How to Count number of people on a rolling period with SQL?

I'm trying to count the number of people who bought a product on a 1 year moving period using SQL.
for example :
In August 2022, the number of people from September 2021 to August 2022
In September 2022, the number of people from October 2021 to September 2022
In October 2022, the number of people from November 2021 to October 2022
....
Here is the code I'm using for now,
I'm doing a for loop to create a query on the 1st 12 months and incrementing by 1 to get the result on each single month. I'd like to know how I can do that by only using SQL and what is the best way to do this.
for i in range(1, 13):
query = f"""
SELECT
FORMAT_DATE("%B %Y", DATETIME_SUB(CURRENT_DATE(), INTERVAL {i} MONTH)),
APPROX_COUNT_DISTINCT(NB_buyer) AS NB_buyer
FROM
Table
WHERE
AND DATE_TRUNC(date, MONTH) BETWEEN DATETIME_SUB(DATE_TRUNC(CURRENT_DATE(), MONTH), INTERVAL {i+12} MONTH)
AND DATETIME_SUB(DATE_TRUNC(CURRENT_DATE(), MONTH), INTERVAL {i-1} MONTH)
{conditions}
UNION ALL
I hope my question is clear
Thanks in advance

Sorting Month And Year Results In Microsoft Access

I have the following table in Microsoft Access
TransactionDate
Market
Details
Opening
Closing
Size
Profit/Loss
I want to run a query that shows the Profit/Loss for each month.
I have been able get a query that returns the information in the following format
TransactionDate By Month Sum Of Sum Of Profit/Loss
April 2014 €1,084.99
April 2015 €674.33
April 2016 €2,057.30
August 2014 €237.59
August 2015 -€267.82
December 2014 €375.88
December 2015 -€1,161.97
February 2015 -€603.87
February 2016 -€124.71
January 2015 €75.11
January 2016 -€1,044.35
But what I want now is for it to display in chronological order as oppose to Alphabetical order.
For example
January 2014
February 2014
March 2014
etc.
I will consider that your TransactionDate field is defined as String
If you want to order by this text field in Access, you will have to use DateValue() function.
That would give:
SELECT TransactionDate FROM yourTable ORDER BY DateValue(TransactionDate)
If your field is already formatted as a Date field, then simply use order by TransactionDate to make it work.

SQL Getting Date Range

I need to aggregate costs to be displayed by date range per month. To illustrate please take a look at the following:
Sample Data
invoice_id usage_date cost
--------------------------------------
123 May 31, 2016 $4
150 June 01, 2016 $4
150 June 02, 2016 $4
150 June 03, 2016 $4
150 June 04, 2016 $5
150 June 05, 2016 $5
...
150 June 30, 2016 $5
240 July 01, 2016 $8
Taking into account the data above, I want to get
Desired Result
range total
-----------------------------
June 01-03, 2016 $12
June 04-30, 2016 $135
As you'll notice I want to group them and add those with the same cost but display the dates as start to end. But this has to be done for each month only. In this particular case, let's say May 31, 2016 incurred a cost of $4, it wouldn't be included even though it has the same cost with the next day (June 01) because they're from different months.
I feel like I need to provide more information but I'm not sure what you guys still need so just comment what you want me to add.
EDIT
I don't know if this matters but let me just add a query I used to generate the sample data I provided above.
Sample Data - SQL
SELECT id.invoice_id, di.usage_date, SUM(di.item_cost) AS cost
FROM detail_items di
LEFT JOIN invoice_details id
ON id.id = di.detail_id
WHERE di.group_id = 123456
GROUP BY id.invoice_id, di.usage_date
Aggregate by year, month and cost and get the min and max dates for a given cost. Then multiply the cost with the total rows in a given month to get the total.
select to_char(mindt,'mm/dd/yyyy')||'-'||to_char(maxdt,'mm/dd/yyyy') daterange,
cnt*cost total
from (
select
cost, min(usage_date) mindt, max(usage_date) maxdt, count(*) cnt,
to_char(usage_date,'mm') usg_mth,to_char(usage_date,'yyyy') usg_yr
from tablename
group by to_char(usage_date,'mm'),to_char(usage_date,'yyyy'),cost
) t

SQL Server 2012: How to order by year then month in chronological order

I have a simple query that averages numbers and breaks them down by year and month. The problem I am having is I can't find a way to order the results by year then month....in chronological order. Here is an example of my results;
Month Year AverageAmount
---------------------------------
April 2012 167582.1139
August 2012 206124.9323
December 2012 192481.8604
February 2012 227612.0485
January 2012 214315.2187
July 2012 195320.075
June 2012 196174.3195
March 2012 201199.9894
May 2012 190526.0571
November 2012 203441.5135
October 2012 216467.7777
September 2012 217635.9174
April 2013 206730.5333
August 2013 197296.0563
As you can see in the table above, the months are in alphabetical order... what I need is the results to be in chronological order, ie...
Month Year AverageAmount
----------------------------------
January 2012 214315.2187
February 2012 227612.0485
March 2012 201199.9894
April 2012 167582.1139
May 2012 190526.0571
June 2012 196174.3195
April 2012 206730.5333
July 2012 195320.075
August 2012 206124.9323
September 2012 217635.9174
October 2012 216467.7777
November 2012 203441.5135
December 2012 192481.8604
January 2013 187268.3027
February 2013 179755.0666
March 2013 200131.6533
Query:
SELECT
datename(month, col1) Month,
year(col2) Year,
avg(col3) AverageAmount
FROM
myDB
GROUP BY
datename(month, datefunded), year(datefunded)
ORDER BY
year(datefunded), datename(month, datefunded)
Any help would be greatly appreciated
Just use this ORDER BY:
ORDER BY
YEAR(datefunded), MONTH(datefunded)
That'll sort your data by the numerical values of year and month of that datefunded
Have a look at this answer: Convert month name to month number in SQL Server
Maybe that solves the sorting for you? You can use one of the suggestions to convert the month to a number, so that e.g. March > 3. Then you sort by that.

Powerpivot: year to date vs year to date previous year

I am using excel 2013 powerpivot which I have linked to a sql query. In this query I have all sales data from previous years and it updates itself with the current sales. I want to make a pivottable showing year to date sales from this year compared to the same period last year. So for example from Jan.1st 2015 until July 10th of 2015 compared to Jan.1st 2014 until July 10th 2014.
I linked my sales data table with a calendar table. But whatever I try, parallelperiod, sameperiodlastyear, totalytd, it always shows me the correct data for this year, but the full year sales of last year. Can anyone recommend me what to try?
thanks,
Frank
The TOTALYTD (and other time intelligence functions) will look for the highest date in whichever context you give it, so when you try to tell it to go back 12 months from now it thinks "OK, I'm in 2014" I'll get ALL the data from 2014 and calculate a TOTALYTD. So you have to ignore the built-in functions and build your own:
=CALCULATE(sum(Table1[sales]),DATESBETWEEN(DateDim[Date], FIRSTDATE(DATEADD(DateDim[Date],-12,MONTH)), LASTDATE(DATEADD(Table1[Date],-12,MONTH))))
So long as you have a slicer or a field on your table that picks up the year, then that should work.
Edit: Having tested with a data sample, again DAX is trying to be too clever and because I have told it to go back 12 MONTHS, it assumes I want ALL data from the month context which is including everything from July last year.
Going back 365 days fixes this (as long as it's not a problem for leap years).
=CALCULATE(sum(Table1[sales]),DATESBETWEEN(DateDim[Date], FIRSTDATE(DATEADD(DateDim[Date],-12,MONTH)), LASTDATE(DATEADD(Table1[Date],-365,DAY))))
I have tried your way, but it does not yet give me the correct answer. Let me show you what I have right now.
For current year sale I have the following Dax formula
=TOTALYTD(sum(Omzetgegevens[NettoOmzet]); Kalender[Calender date])
For the previous year sale I have:
=CALCULATE((SUM(Omzetgegevens[NettoOmzet])); SAMEPERIODLASTYEAR(DATESYTD(Kalender[Calender date])))
To test your solution I have called "test ytd":
=CALCULATE(SUM(Omzetgegevens[NettoOmzet]); DATESBETWEEN(Kalender[Calender date]; FIRSTDATE(DATEADD(Kalender[Calender date];-12; MONTH)); LASTDATE(DATEADD(Kalender[Calender date]; -365; DAY))))
If I run the pivottable now, the result I get is:
2015
current year ytd last year ytd test ytd
januari 28.912 34.487 34.487
februari 50.301 66.003 31.516
maart 73.362 92.647 26.644
april 99.561 117.853 25.205
mei 128.021 149.108 31.255
juni 149.706 174.076 24.968
juli 158.297 205.438 31.362
augustus 158.297 231.693 26.255
september 158.297 254.534 22.841
oktober 158.297 282.484 27.951
november 158.297 303.808 21.324
december 158.297 313.208 9.400
Total 158.297 313.208 313.208
What I would like to see is the following. As this report was run on the 14th of july 2015. I want to see all sales for 2015 until this date and all the sales for 2014 until july 14th 2014.
If it is not possible to see the months, I am also fine with only a total number for current ytd and last year ytd
2015
current year ytd last year ytd
januari 28.912 34.487
februari 50.301 66.003
maart 73.362 92.647
april 99.561 117.853
mei 128.021 149.108
juni 149.706 174.076
juli 158.297 175.312(so not full month of july in 2014)
Total 158.297 175.312
Recently had a similar issue. Current context confuse a lot and did not return the result we think should be returned. Play with DATEADD to go back and forth in combination with any of the date/time function. You will get the result and the context will also be clear.