SQL Sum with conditions in two columns - sql

I'm very new to SQL and VB.NET. I have an existing table called STOCK with the columns shown here, and I want to sum buy and sell to display current quantity.
Existing table:
ID
Date
BUY
SELL
Current quantity
1
01/01/22
88
0
2
03/01/22
22
0
94669
05/02/22
0
30
I want to display in Current quantity like this
(the current quantity amount in the row above + BUY - SELL)
I add result in Current quantity manually, but I want to do this in automatic way it is possible in SQL code
ID
Date
BUY
SELL
Current quantity
1
01/01/22
88
0
88
2
03/01/22
22
0
110
3
05/02/22
0
30
80

You can try this:
select a.*,
sum(net_sell) over (order by Curr_date ) as Current_quantity
from
(select s.*,
buy-sell as net_sell
from stock s) a ;
Dbfiddle link : https://dbfiddle.uk/?rdbms=postgres_11&fiddle=196a41a578d1e699ccaa3e878e261019

Related

SQL Coding for Logical Operators question

Q:
Using the retail. Inventory table, calculate what the total inventory would be for each product with 5 or less items in stock if all of the items on order were delivered immediately without any other sales taking place. The product_id for each product should be the first column in your results.
I need a sql code the one I am using is not working and I dont know another way to get the result my professor is asking for.
Expected:
product_id ?column?
3 20
4 37
6 13
8 4
10 24
24 41
31 4
41 35
42 2
58 25
71 28
this is what I am using, but like I said it's wrong:
select product_id
from retail.inventory
where total_on_hand <= 5;
SELECT product_id, SUM(quantity_on_hand + quantity_on_order) AS total_inventory
FROM retail.inventory
WHERE quantity_on_hand + quantity_on_order <= 5
GROUP BY product_id
This query first selects the product_id and calculates the total inventory for each product by adding the quantity_on_hand and quantity_on_order columns. It then filters the results to only include products with 5 or less items in stock, and finally groups the results by product_id to calculate the total inventory for each product.
SELECT product_id, SUM(quantity_on_hand + quantity_on_order) AS total_inventory_name
FROM retail_inventory_tablename
WHERE quantity_on_hand <= 5
GROUP BY product_id
You may try above
Took this class - the answer is:
SELECT product_id, total_on_hand + total_on_order
FROM retail.inventory
WHERE total_on_hand <= 5

rolling sum to calculate YTD for each month group by product and save to separate columns using SQL

I have a data like this:
Order_No Product Month Qty
3001 r33 1 8
3002 r34 1 11
3003 r33 1 17
3004 r33 2 3
3005 r34 2 11
3006 r34 3 1
3007 r33 3 -10
3008 r33 3 18
I'd like to calculate total YTD qty for product and each month and save to separate columns. Below is what I want
Product Qty_sum_jan Qty_sum_feb Qty_sum_mar
r33 25 28 36
r34 11 22 23
I know how to use window function to calculate rolling sums but I have no idea to group them to separate columns. I currently use something like this:
case when Month = 1 then sum(Qty) over(partition by Product order by Month) else 0 end as Qty_sum_jan,
case when Month <=2 then sum(Qty) over(partition by Product order by Month) else 0 end as Qty_sum_feb,
case when Month <=3 then sum(Qty) over(partition by Product order by Month) else 0 end as Qty_sum_mar,
This will get me rolling sum by order but how to get to product level like what I show above? If I use group by then it will throw an error since Month is not in group by clause. I also cannot just use max to get the last value since qty can be negative so the last value may not be maximum. I use sparkSQL by the way
To my understanding, there is no need to use window functions. The following query achieves your desired output:
select
product,
sum(case when month = 1 then qty else 0 end) as sum_qty_jan,
sum(case when month <= 2 then qty else 0 end) as sum_qty_feb,
sum(case when month <= 3 then qty else 0 end) as sum_qty_mar
from your_table
group by 1;
Output:
product
sum_qty_jan
sum_qty_feb
sum_qty_mar
r33
25
28
36
r34
11
22
23

SQL - Case when product exists, fill up its corresponding value to all rows within the partition

I have the something like the following monthly data set.
I have a Product, company ID, Date, and Quantity. A company (denoted by Company ID) can buy multiple products. I want to create a new column that will have the quantity of Product 'C' if the company bought in the month at each line item. If Product 'C' is not bought, then return 0.
Product Company_ID Date Quantity Desired_Calculated_Column
A 1 5/1/2019 100 300
B 1 5/1/2019 200 300
C 1 5/1/2019 300 300
A 2 6/1/2019 150 125
B 2 6/1/2019 250 125
C 2 6/1/2019 125 125
A 3 7/1/2019 175 0
B 3 7/1/2019 275 0
I have been trying to partition the data based on Product and Company ID. I have been trying to leverage the LAST_VALUE but haven't been successful.
LAST_VALUE(quantity) OVER (PARTITION BY Date, Company_ID
ORDER BY product_group
) AS Desired_Calculated_Column
You don't want last_value(). You can use conditional aggregation, assuming that 'C' occurs once per group:
MAX(CASE WHEN product_group = 'C' THEN quantity ELSE 0 END) OVER
(PARTITION BY Date, Company_ID) AS C_quantity

SQL How to calculate Average time between Order Purchases? (do sql calculations based on next and previous row)

I have a simple table that contains the customer email, their order count (so if this is their 1st order, 3rd, 5th, etc), the date that order was created, the value of that order, and the total order count for that customer.
Here is what my table looks like
Email Order Date Value Total
r2n1w#gmail.com 1 12/1/2016 85 5
r2n1w#gmail.com 2 2/6/2017 125 5
r2n1w#gmail.com 3 2/17/2017 75 5
r2n1w#gmail.com 4 3/2/2017 65 5
r2n1w#gmail.com 5 3/20/2017 130 5
ation#gmail.com 1 2/12/2018 150 1
ylove#gmail.com 1 6/15/2018 36 3
ylove#gmail.com 2 7/16/2018 41 3
ylove#gmail.com 3 1/21/2019 140 3
keria#gmail.com 1 8/10/2018 54 2
keria#gmail.com 2 11/16/2018 65 2
What I want to do is calculate the time average between purchase for each customer. So lets take customer ylove. First purchase is on 6/15/18. Next one is 7/16/18, so thats 31 days, and next purchase is on 1/21/2019, so that is 189 days. Average purchase time between orders would be 110 days.
But I have no idea how to make SQL look at the next row and calculate based on that, but then restart when it reaches a new customer.
Here is my query to get that table:
SELECT
F.CustomerEmail
,F.OrderCountBase
,F.Date_Created
,F.Total
,F.TotalOrdersBase
FROM #FullBase F
ORDER BY f.CustomerEmail
If anyone can give me some suggestions, that would be greatly appreciated.
And then maybe I can calculate value differences (in percentage). So for example, ylove spent $36 on their first order, $41 on their second which is a 13% increase. Then their second order was $140 which is a 341% increase. So on average, this customer increased their purchase order value by 177%. Unrelated to SQL, but is this the correct way of calculating a metric like this?
looking to your sample you clould try using the diff form min and max date divided by total
select email, datediff(day, min(Order_Date), max(Order_Date))/(total-1) as avg_days
from your_table
group by email
and for manage also the one order only
select email,
case when total-1 > 0 then
datediff(day, min(Order_Date), max(Order_Date))/(total-1)
else datediff(day, min(Order_Date), max(Order_Date)) end as avg_days
from your_table
group by email
The simplest formulation is:
select email,
datediff(day, min(Order_Date), max(Order_Date)) / nullif(total-1, 0) as avg_days
from t
group by email;
You can see this is the case. Consider three orders with od1, od2, and od3 as the order dates. The average is:
( (od2 - od1) + (od3 - od2) ) / 2
Check the arithmetic:
--> ( od2 - od1 + od3 - od2 ) / 2
--> ( od3 - od1 ) / 2
This pretty obviously generalizes to more orders.
Hence the max() minus min().

Performing calculations based on dates in oracle

I have the following tables.
Accounts(account_number*,balance)
Transactions(account_number*,transaction_number*,date,amount,type)
Date is the date that the transaction happened. Amount is the amount of the transaction
and it can have a positive or a negative value, dependent of the type(Withdrawal -,Deposit +). I think the type is irrelevant here as the amount is already given in the proper way.
I need to write a query which points out the account_number of the accounts that have at least once had negative balance.
Here's some sample data from the Transactions table, ordered by account_number and date.
account_number transaction_number date amount type
--------------------------------------------------------------------
1 2 02/03/2013 -20000 withdrawal
1 3 03/15/2013 300 deposit
1 1 01/01/2013 100 deposit
2 1 04/15/2013 235236 deposit
3 1 06/15/2013 500 deposit
4 1 03/01/2013 10 deposit
4 2 04/01/2013 80 deposit
5 1 11/11/2013 10000 deposit
5 2 12/11/2013 20000 deposit
5 3 12/13/2013 -10002 withdrawal
6 1 03/15/2013 102300 deposit
7 1 03/15/2013 100 deposit
8 1 08/08/2013 133990 deposit
9 1 05/09/2013 10000 deposit
9 2 06/01/2013 300 deposit
9 3 10/11/2013 23 deposit
Something like this with an analytic to keep a running balance for an account:
SELECT DISTINCT account_number
FROM ( SELECT account_number
,SUM(amount)
OVER (PARTITION BY account_number ORDER BY date) AS running_balance
FROM transactions
) x
WHERE running_balance < 0
Explanation:
It is using an analytic function: the PARTITION BY breaks the table into groups identified by the account number. Within each group, the data is ordered by date. Then there is a walk through each element in the ordered group and the SUM function is applied (by default summing everything from the beginning of the group to the current row). This gives you a running balance. Just run the inner query on its own and take a look at the output, then read a bit about analytic queries. They are pretty cool.