Have customer payments , i want to calculate who are the top 10 customers per day based on sum of amount per day per customer. Eventually i want to display those 10 customers and their payment per hour (sum of the amount per hour)
I tried to create 2 window functions in bigquery one window function for per customer and per hour (Value_Hr) values, and one more window function for sum of values per customer (Value_customer).
with base as (
select Name, sum(amount) over W1 as Value_Hr, Hour, sum(amount) over w2 as Value_customer
from
(SELECT trim(cast(format('%t',Name) as string) ) as Name,
cast(round(amount) as numeric) as amount , extract(hour from SettlementTimestamp) as Hr
FROM Payments
where length(trim(Name))>0
)
qualify row_number() over (partition by Name,hr )=1
window w1 as (partition by Name,hr ),
w2 as (partition by Name)
)
select Name,Value_Hr,Hour ,Value_customer
from base
qualify row_number() over (partition by Value_customer order by Value_customer desc )<=10
I expect data as below
but row_number is calculating with in the group of customers and hourly amounts instead per customer and its total value
Can anyone help ?
Related
I am trying to find the maximum number of consecutive trading holidays from a Trading date/calendar table. I have a flag isTradingHoliday = 1 in the TradingDate table that denotes the dates which are trading holidays, otherwise isTradingHoliday = 0. How to know which date range was the most consecutive trading holidays in that TradingDate table?
This sounds like a gaps-and-islands problem. You can find the first date and the count of days using the difference of row numbers. The rest is aggregation and filtering:
select top (1) with ties min(tradingdate) as startdate,
max(tradingdate) as enddate
from (select c.*,
row_number() over (order by tradingdate) as seqnum,
row_number() over (partition by isTradingHoliday order by tradingdate) as seqnum_h
from calendar c
) c
where isTradingHoliday = 1
group by isTradingHoliday, (seqnum - seqnum_h)
order by count(*) desc
I have a data set with user ids that have made purchases over time. I would like to show a YTD distinct count of users that have made a purchase, partitioned by State and Country. The output would have 4 columns: Country, State, Year, Month, YTD Count of Distinct Users with purchase activity.
Is there a way to do this? The following code works when I exclude the month from the view and do a distinct count:
Select Year, Country, State,
COUNT(DISTINCT (CASE WHEN ActiveUserFlag > 0 THEN MBR_ID END)) AS YTD_Active_Member_Count
From MemberActivity
Where Month <= 5
Group By 1,2,3;
The issue occurs when the user has purchases across multiple months, because I can’t aggregate at a monthly level then sum, because it duplicates user counts.
I need to see the YTD count for each month of the year, for trending purposes.
Return each member only once for the first month they make a purchase, count by month and then apply a Cumulative Sum:
select Year, Country, State, month,
sum(cnt)
over (partition by Year, Country, State
order by month
rows unbounded preceding) AS YTD_Active_Member_Count
from
(
Select Year, Country, State, month,
COUNT(*) as cnt -- 1st purchses per month
From
( -- this assumes there's at least one new active member per year/month/country
-- otherwise there would be mising rows
Select *
from MemberActivity
where ActiveUserFlag > 0 -- only active members
and Month <= 5
-- and year = 2019 -- seems to be for this year only
qualify row_number() -- only first purchase per member/year
over (partition by MBR_ID, year
order by month --? probably there's a purchase_date) = 1
) as dt
group by 1,2,3,4
) as dt
;
Count users in the first month they appear:
select Country, State, year, month,
sum(case when ActiveUserFlag > 0 and seqnum = 1 then 1 else 0 end) as YTD_Active_Member_Count
from (select ma.*,
row_number() over (partition by year order by month) as seqnum
from MemberActivity ma
) ma
where Month <= 5
group by Country, State, year, month;
It's been a while since I used SQL so I'm a bit rusty. Let's say you want to compare the cost of things purchased from the previous month to this month. So an example would be a data table like this...
An item purchased on October cost $3 but the same item cost in September was $2 and $1. So you'd get the max cost of the max date (which would then be the $2 not $1). This would happen for every row of data.
I've done this with a stored scalar-value function, but when handling 100K+ rows of data, speeds are no where near fast. How would you do this with a select query in itself? What I did before was select both the max's in a select statement and only return 1, then call that function in a select statement. I want to do the same without stored procedures or functions for speed reasons. I know the following query won't work because you can only return 1 value, but it's something that I'm going for.
Select
Purchase, Item, USD,
(select MAX(Purchase), MAX(USD) from Table
where Item = 845 and MONTH(Purchase) = MONTH(Purchase) -1) LastCost
from Table
An example of what it should display can be portrayed as this.
What would be the best way to approach this?
Attention:
Select MAX(Purchase), MAX(USD) from Table will not return the highest cost for the highest date, but will return the highest date and the highest cost (no matter of what date).
This is how I would do this (on at least SQL Server 2012):
To get only one record per month and item (with the highest cost on the latest date), I use a numbering for the purchase date and cost (per item and month) with a descending sort order, first by date, then by cost. In the next step, I filter out only those records where the numbering is 1 (max cost for max date per item and month) and use the LAG function to access the previous cost:
WITH
numbering (Purchase, Item, Cost, p_no) AS (
SELECT Purchase,Item, Cost
,ROW_NUMBER() OVER (PARTITION BY Item, EOMONTH(Purchase) ORDER BY Purchase DESC, Cost DESC)
FROM tbl
)
SELECT Purchase, Item, Cost
, LAG(Cost) OVER (PARTITION BY Item ORDER BY Purchase) AS LastCost
FROM numbering
WHERE p_no = 1
SELECT Date, item, usd,
LAG(Date, 1) OVER(Order by date asc) as FormerDate,
LAG(usd, 1) OVER(Order by date asc) as FormerUsd
from (select date, item, max(usd) as usd from Data group by date, item) t
This basically returns the day before the current entry with its max price.
For SQL server 2017 below query will work for sample data
select purchase,item,
substring(usd,CHARINDEX(',',usd),len(usd)) as USD,
substring(usd,1,CHARINDEX(',',usd)) as lastcost from
(select max(purchase) as purchase,item, STRING_AGG (usd, ',') AS usd
from
(
select purchase,item,max(usd) as usd from t
group by purchase,item
) as T group by item
) T1
For your results, you need to use MAX() and ROW_NUMBER() with OVER(). Then partition the records by Item, Year, and Month. This will assure that the sort will be on each item, by each year, by each month. The ROW_NUMBER() will act as as simple way to put the last records at the top of the results, so you'll call row number 1 for each item to get the latest cost. After that, you use it as subquery to refine it as needed. For a start (your sample), you'll need to use CASE in order to split the USD (previous and Last cost). then you do the rest from there (simple methods).
I need to note that it's important to sort the records by year first, then month. then if you need to include the day, include it. This way you'll insure the records will be sorted correctly.
So, the query would look like something like this :
SELECT
MAX(Purchase) Purchase
, MAX(Item) Item
, MAX(CASE WHEN LastCost > USD THEN LastCost ELSE NULL END) USD
, MAX(CASE WHEN LastCost = USD THEN LastCost ELSE NULL END) LastCost
FROM (
SELECT
Purchase
, Item
, USD
, MAX(USD) OVER(PARTITION BY Item, YEAR(Purchase), MONTH(Purchase)) LastCost
, ROW_NUMBER() OVER(PARTITION BY Item, YEAR(Purchase), MONTH(Purchase) ORDER BY MONTH(Purchase)) RN
FROM Table
) D
WHERE
RN = 1
with data as (
select Item, eomonth(Purchase) as PurchaseMonth, max(USD) as MaxUSD
from T
group by Item, eomonth(Purchase)
)
select
PurchaseMonth, Item,
lag(MaxUSD) over (partition by Item order by PurchaseMonth) as PriorUSD
from data;
I want to show a graph with income from different parties over the last 6 months, but based on the top income of 10 people only based on the last month.
So this can change each month as the top 10 people can change when they deposit more money, so the graph will show these 10 people's deposits of the last 6 months, based on the last month deposit only.
I already used a LAG function and a RANK() OVER PARTITION function.
I don't understand why you'll need rank or lag functions.
You can simply use an IN statement:
SELECT * FROM YourTable t
WHERE t.depositDate between StartRangeDate and EndRangeDate
AND t.ID in(select ID from(SELECT s.id,sum(s.depositAmount) as total
from YourTable s
where s.date between ThisMonthStart and ThisMonthEnd
group by s.id)
order by total
limit 10)
You can play with the first select to select what ever you want/add a group by and sum them or I don't know.
I'm having an odd problem
I have a table with the columns product_id, sales and day
Not all products have sales every day. I'd like to get the average number of sales that each product had in the last 10 days where it had sales
Usually I'd get the average like this
SELECT product_id, AVG(sales)
FROM table
GROUP BY product_id
Is there a way to limit the amount of rows to be taken into consideration for each product?
I'm afraid it's not possible but I wanted to check if someone has an idea
Update to clarify:
Product may be sold on days 1,3,5,10,15,17,20.
Since I don't want to get an the average of all days but only the average of the days where the product did actually get sold doing something like
SELECT product_id, AVG(sales)
FROM table
WHERE day > '01/01/2009'
GROUP BY product_id
won't work
If you want the last 10 calendar day since products had a sale:
SELECT product_id, AVG(sales)
FROM table t
JOIN (
SELECT product_id, MAX(sales_date) as max_sales_date
FROM table
GROUP BY product_id
) t_max ON t.product_id = t_max.product_id
AND DATEDIFF(day, t.sales_date, t_max.max_sales_date) < 10
GROUP BY product_id;
The date difference is SQL server specific, you'd have to replace it with your server syntax for date difference functions.
To get the last 10 days when the product had any sale:
SELECT product_id, AVG(sales)
FROM (
SELECT product_id, sales, DENSE_RANK() OVER
(PARTITION BY product_id ORDER BY sales_date DESC) AS rn
FROM Table
) As t_rn
WHERE rn <= 10
GROUP BY product_id;
This asumes sales_date is a date, not a datetime. You'd have to extract the date part if the field is datetime.
And finaly a windowing function free version:
SELECT product_id, AVG(sales)
FROM Table t
WHERE sales_date IN (
SELECT TOP(10) sales_date
FROM Table s
WHERE t.product_id = s.product_id
ORDER BY sales_date DESC)
GROUP BY product_id;
Again, sales_date is asumed to be date, not datetime. Use other limiting syntax if TOP is not suported by your server.
Give this a whirl. The sub-query selects the last ten days of a product where there was a sale, the outer query does the aggregation.
SELECT t1.product_id, SUM(t1.sales) / COUNT(t1.*)
FROM table t1
INNER JOIN (
SELECT TOP 10 day, Product_ID
FROM table t2
WHERE (t2.product_ID=t1.Product_ID)
ORDER BY DAY DESC
)
ON (t2.day=t1.day)
GROUP BY t1.product_id
BTW: This approach uses a correlated subquery, which may not be very performant, but it should work in theory.
I'm not sure if I get it right but If you'd like to get the average of sales for last 10 days for you products you can do as follows :
SELECT Product_Id,Sum(Sales)/Count(*) FROM (SELECT ProductId,Sales FROM Table WHERE SaleDAte>=#Date) table GROUP BY Product_id HAVING Count(*)>0
OR You can use AVG Aggregate function which is easier :
SELECT Product_Id,AVG(Sales) FROM (SELECT ProductId,Sales FROM Table WHERE SaleDAte>=#Date) table GROUP BY Product_id
Updated
Now I got what you meant ,As far as I know it is not possible to do this in one query.It could be possible if we could do something like this(Northwind database):
select a.CustomerId,count(a.OrderId)
from Orders a INNER JOIN(SELECT CustomerId,OrderDate FROM Orders Order By OrderDate) AS b ON a.CustomerId=b.CustomerId GROUP BY a.CustomerId Having count(a.OrderId)<10
but you can't use order by in subqueries unless you use TOP which is not suitable for this case.But maybe you can do it as follows:
SELECT PorductId,Sales INTO #temp FROM table Order By Day
select a.ProductId,Sum(a.Sales) /Count(a.Sales)
from table a INNER JOIN #temp AS b ON a.ProductId=b.ProductId GROUP BY a.ProductId Having count(a.Sales)<=10
If this is a table of sales transactions, then there should not be any rows in there for days on which there were no Sales. I.e., If ProductId 21 had no sales on 1 June, then this table should not have any rows with productId = 21 and day = '1 June'... Therefore you should not have to filter anything out - there should not be anything to filter out
Select ProductId, Avg(Sales) AvgSales
From Table
Group By ProductId
should work fine. So if it's not, then you have not explained the problem completely or accurately.
Also, in yr question, you show Avg(Sales) in the example SQL query but then in the text you mention "average number of sales that each product ... " Do you want the average sales amount, or the average count of sales transactions? And do you want this average by Product alone (i.e., one output value reported for each product) or do you want the average per product per day ?
If you want the average per product alone, for just thpse sales in the ten days prior to now? or the ten days prior to the date of the last sale for each product?
If the latter then
Select ProductId, Avg(Sales) AvgSales
From Table T
Where day > (Select Max(Day) - 10
From Table
Where ProductId = T.ProductID)
Group By ProductId
If you want the average per product alone, for just those sales in the ten days with sales prior to the date of the last sale for each product, then
Select ProductId, Avg(Sales) AvgSales
From Table T
Where (Select Count(Distinct day) From Table
Where ProductId = T.ProductID
And Day > T.Day) <= 10
Group By ProductId