SQL - Monthly cumulative count of new customer based on a created date field - sql

Thanks in advance.
I have Customer records that look like this:
Customer_Number
Create_Date
34343
01/22/2001
54554
03/03/2020
85296
01/01/2001
...
I have about a thousand of these records (customer number is unique) and the bossman wants to see how the number of customers has grown over time.
The output I need:
Customer_Count
Monthly_Bucket
7
01/01/2021
9
02/01/2021
13
03/01/2021
20
04/01/2021
The customer count is cumulative and the Monthly Bucket will just feed the graphing package to make a nice bar chart answering the question "how many customers to we have in total in a particular month and how is it growing over time".

Try the following SELECT SQL with a sub-query:
SELECT Customer_Count=
(
SELECT COUNT(s.[Create_Date])
FROM [Customer_Sales] s
WHERE MONTH(s.[Create_Date]) <= MONTH(t.[Create_Date])
), Monthly_Bucket=MONTH([Create_Date])
FROM Customer_Sales t
WHERE YEAR(t.[Create_Date]) = ????
GROUP BY MONTH(t.[Create_Date])
Where [Customer_Sales] is the sales table and ??? = your year

Related

How to compare and find the highest average number of a value occurance in SQL for specific months?

I am fairly new to SQL and need help to find which customer has the highest average number of event occurring by month in the years (2019 - 2020) and which is the top 3 busy month every year?
Please note one customer can have multiple event_IDs.
Table Snippet:
event_ID
cust_ID
event_datetime
abc123
cus11
2019-03-13T00:00:00
abc124
cus12
2020-05-23T02:34:35
abc125
cus457
2018-12-12T22:12:23
abc126
cus11
2017-01-07T13:54:56
abc127
cus7897
2021-07-11T04:43:23
I need to find the customers having the highest average number of events in the respective month( cust with highest number of events on avg in 2019, 2020, 2021).
month
cust_ID
avg_num
1
cus11
9345.8
2
cus4563
11898.5
I have tried using CTE and window functions but couldn't figure out the logic to get to the result, any help is appreciated!
EDIT:
For clarification, my example is just a snippet of the table, the actual table has more than a few million rows, I need the customer who has the maximum number of events occurring on average over month 1,2,3,.. and avg_num will have the average value of the number of event for the cust_ID with max number of event-[ (num of event in 2019 + 2020 + 2021)/3 ]
Maybe something like this:
SELECT cust_id
, COUNT(*) AS number_of_events
, EXTRACT(YEAR FROM MAX(event_datetime)) last_year_for_cust_id
, EXTRACT(YEAR FROM MIN(event_datetime)) first_year_for_cust_id
, CAST(COUNT(*) AS DECIMAL) / (EXTRACT(YEAR FROM MAX(event_datetime)) - EXTRACT(YEAR FROM MIN(event_datetime)) )
FROM table_name
GROUP BY cust_id
ORDER BY cust_id; -- or something else
I didn't test it, no idea what brand of database you use and no DB<>fiddle was available.

How to create a dynamic query which looks at x date gives me all records for 2 weeks before and after x date?

I am using HANA and I have two tables. Both tables have
Customer_Number
Transaction_Number
Transaction_Date
Transaction_Week
Spend
Means_of_Payment
The only difference in the TYPE of information between the tables is the Means_of_Payment. Table 1 has transactions paid with the debit card or credit card and table 2 has transactions paid with a gift card or a voucher. The customers in table 1 are the same as customers in table 2
Focus: Customers use gift card/vouchers mostly in Apr
My aim: What is a customer’s spend 2 weeks before their transaction in April and 2 weeks after their transaction in April. Idea is to see if and how their spend changed after using a gift card/voucher
Problem: Each customer’s Apr transaction date will be different so I need to create a dynamic query that will look up a customer’s transaction date in the month of April (table 2) and give me their spend 2 weeks before and after that date (table 1) and I’m really unsure about how to do this.
Expected Result: Customer 1 Apr transaction date = 1/04/2018 so their relevant date range is 2 weeks before 1/04/2018 and 2 weeks after.
Customer 2 Apr transaction date = 5/04/2018 so their relevant date range in 2 weeks before 5/04/2018 and 2 weeks after.
I want to return the transaction_number, spend and Means_of_payment in each customer's relevant date range
Any ideas?
Thanks in advance, I appreciate your help 😊
I only have code that is joining the two tables
SELECT *
FROM "Table2" AS A
LEFT JOIN "Table1" AS B
ON A.CUSTOMER = B.CUSTOMER_NUMBER
Try this one:
SELECT cards.*
FROM "Table2" AS coupons
JOIN "Table1" AS cards
ON coupons.CUSTOMER = coupons.CUSTOMER_NUMBER
and cards.Transaction_Date between ADD_DAYS(coupons.Transaction_Date, -14) and
ADD_DAYS(coupons.Transaction_Date, 14)

Pulling data with sysdate using for loop?

I am pulling data and need to get a running iterative count of people that fall within the effective and expire date columns. For example I need to get a count of members that fall within a month:
m.memid m.effective_dt m.expiration_dt
00010 3/1/14 7/31/15
00011 1/1/12 1/31/14
00012 10/1/13 1/31/15
select mar2015.nummem032015
, apr2015.nummem042015
from (
select count(distinct m.member) as nummem032015
from m
where to_date('31-mar-2015') between trunc(m.EFFECTIVE_DT) and
trunc(m.EXPIRATION_DT
) mar2015
, (
select count(distinct m.member) as nummem042015
from m
where to_date('30-apr-2015') between trunc(m.EFFECTIVE_DT) and
trunc(m.EXPIRATION_DT
) apr2015
I am looking for a way to not have to do this for each month.
Output to look something like this:
month count
mar2015 1000
apr2015 2010
may2015 1900
Thank you.

SQL Daily Totals

Ok so what I am trying to make is a ssrs report that gets daily totals of clients seen per employee and list that day by day. So the top row would show every day in a month e.g 1st ,2nd,3rd. The first column should show the names of the employee.
I'm pretty sure I nee to use a matrix to do this but am unsure how to go about this with listing out the days. If anyone can help me or point me in the right direction that would be great.
To add more info I have a table called Employees with all the employees I want to list and a table appointments with all the clients that the employees have seen. I want to total the clients seen for each employee for every day of the month with the days listed across the top of the table.
for example
| 1st | 2nd | 3rd | 4th | 5th | 6th | 7th .....
emp1 2 3 5 4 5 5 6
emp2 3 4 5 9 1 3 5
emp3 1 0 0 4 5 9 2
emp4 8 3 7 2 9 3 4
If you want your rows to be columns, you need to use pivot like so:
Example:
SELECT VendorID, [250] AS Emp1, [251] AS Emp2, [256] AS Emp3, [257] AS Emp4, [260] AS Emp5
FROM
(SELECT PurchaseOrderID, EmployeeID, VendorID
FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( [250], [251], [256], [257], [260] )
) AS pvt
ORDER BY pvt.VendorID;
If you want your columns to be rows, you would use UNPIVOT.
You are correct to use a matrix.
Assuming you already have a query selecting the necessary information and joining properly:
Create a Column Group, grouping by the appointment date. Format your column header using Day(Fields!AppointmentDateTime.Value) to get the value from 1 to 31.
Create a Row Group, grouping by Employee. In the data cell, total the visits by using =Count(AppointmentDateTime.Value).
If this report will span several months, include a parent column group where you group by Month(Fields!AppointmentDateTime.Value). You can also add totals by right-clicking on a textbox in the row group and selecting "Add Total".

sql DB calculation moving summary‏‏‏‏‏

I would like to calculate moving summary‏‏‏‏‏:
Total amount:100
first receipt: 20
second receipt: 10
the first row in calculation column is a difference between total amount and the first receipt: 100-20=80
the second row in calculation column is a difference between the first calculated_row and the first receip: 80-10=70
The presentation is supposed to present receipt_amount, balance:
receipt_amount | balance
20 | 80
10 | 70
I'll be glad to use your help
Thanks :-)
You didn't really give us much information about your tables and how they are structured.
I'm assuming that there is an orders table that contains the total_amount and a receipt_table that contains each receipt (as a positive value):
As you also didn't specify your DBMS, this is ANSI SQL:
select sum(amount) over (order by receipt_nr) as running_sum
from (
select total_amount as amount
from orders
where order_no = 1
union all
select -1 * receipt_amount
from the_receipt_table
where order_no =
) t
First of all- thanks for your response.
I work with Cache DB which can be used both SQL and ORACLE syntax.
Basically, the data is locaed in two different tables, but I have them in one join query.
Couple of rows with different receipt amounts and each row (receipt) has the same total amount.
Foe example:
Receipt_no Receipt_amount Total_amount Balance
1 20 100 80
1 10 100 70
1 30 100 40
2 20 50 30
2 10 50 20
So, the calculation is supposed to be in a way that in the first receipt the difference calculation is made from the total_amount and all other receipts (in the same receipt_no) are being reduced from the balance
Thanks!