Find sum based on another column and use aggregate function in SQL - sql

I am working on SQL and I want to achieve this output in SQL using HIVE, here is the problem statement
I have columns Item, Cost and price.
The output I am expecting to have a following columns
25% cost- Which is the 25% value of cost.
total_price- Its a sum of price values based on Item.
cumulative_price-Based on item it's a sum of cumulative price.
I want to flag those records which has cumulative_price>25%cost value

this code will work on sql so try it.
with cte as
(select *,(cost*0.25) as costx,
sum(price) over (PARTITION BY item order by item) AS total_price,
sum(price) over (PARTITION BY item order by item,price) cumulative_price from dept)
select *,case when cumulative_price<costx then 0 else 1 end as flag from cte;
its work on me.

Related

Summing values based on values in other column (Variable)

I would like to sum all items within the query based on their ITEM, keep in mind this query is a daily report that will pick up different ITEM's depending on which items were purchased that day. Therefore, a basic CASE wont work.
For example:
ITEM_TABLE: expected result
Item Type Amount SUM
----------------------------------
SCARF 10 10
T-Shirt 20 45
T-Shirt 25 45
Current Query:
select SUM(AMOUNT)
from EDSREP.V_COGNOS_WSSTOR_SETTLE_RECON a
having CCY_CODE = a.CCY_CODE
Nothing is showing up, please help.
You can use window functions:
select
item_type,
amount,
sum(amount) over(partition by item_type) sum_amount
from item_table

Redshift - Find % as compared to total value

I have a table with count by product. I am trying to add a new column that would find % as compared to sum of all rows in that column.
prod_name,count
prod_a,100
prod_b,50
prod_c,150
For example, I want to find % of prod_a as compared to the total count and so on.
Expected output:
prod_name,count,%
prod_a,100,0.33
prod_b,50,0.167
prod_c,150,0.5
Edit on SQL:
select count(*),ratio_to_report(prod_name)
over (partition by count(*))
from sales
group by prod_name;
Using window functions.
select t.*,100.0*cnt_by_prod/sum(cnt_by_prod) over() as pct
from tbl t
Edit: Based on OP's question change, To compute the counts and then percentage, use
select prod_name,100.0*count(*)/sum(count(*)) over()
from tbl
group by prod_name

query Get Balances in Oracle table stock

i have sample data in oracle data table namely STOKREWARD table, i wanna get balance between quantity IN and quantity OUT.
i wanna get value BALANCES like this:
i try using query like this, but the result doesn't i want
SELECT STOKREWARD.NO, STOKREWARD.DODATE, STOKREWARD.REWARDNAME, STOKREWARD.NOTES,
STOKREWARD.QTYIN, STOKREWARD.QTYOUT,
(STOKREWARD.QTYIN- STOKREWARD.QTYOUT) AS BALANCES
FROM STOKREWARD
ORDER BY STOKREWARD.NO ASC
this query gives result:
anyone can help me? thanks
Using SUM() OVER:
SELECT NO, DODATE, CODE, REWARDNAME, NOTES, QTYIN, QTYOUT,
SUM (QTYIN - QTYOUT) OVER (ORDER BY DODATE ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS BALANCES
FROM STOKREWARD

understanding group by statements in rails

Given a invoices table like this:
invoice_date customer total
2012/01/01 A 780
2013/05/01 A 3800
2013/12/01 A 1500
2012/07/01 B 15
2013/03/01 B 21
Say that i want both:
the count of invoices of each customer of each year
the sum of the amounts of all the invoices of each customer of each year
the max amount among all the invoices of each customer of each year
That is, in SQL, very easily:
SELECT CUSTOMER, YEAR(invoice_date) as INVOICE_YEAR, MAX(total) AS MAX_TOTAL, SUM(total) AS SUM_AMOUNTS, count(*) AS INVOICES_NUM AS SUM_TOTAL FROM invoices GROUP BY YEAR(invoice_date), CUSTOMER;
(the function to extract the year of a date may be YEAR(date) or something else depending on the database server, on sqllite is strftime('%y', invoice_date))
Ok, i've tryed to translate this in rails/ActiveRecord:
Invoice.count(:group => 'customer')
This works, but how can i get both count and sum and max?
The idea i'm familiar with is that (in SQL) a group by generates the rows (well, to be correct, determines which rows should exist in the result table), and then you pass an arbitrary number of aggregation functions that are applyed on every disaggregate set of rows that are behind a single result row. E.G: group by customer means: one row for Customer A, one row for customer B; then I can pass how many aggregation function i want: count(*), max(total), max(date), min(total) just to list the most common.
Looking at the rails ActiveRecord API it seems that you're supposed to do just one function at a time, because the group is an argument of the count. And if i want a multiple aggregation functions, say max, sum etc?
Second attempt
irb> i = Invoice.select('customer, sum(total)').group('customer')
Invoice Load (0.3ms) SELECT customer, sum(total) AS TOTAL_GROUP FROM "invoices" GROUP BY customer
=> [#, #]
That is: it doesn't give back the field with the sum...
Well it does, it just doesn't get printed out.
Say you query is i = Invoice.select('customer, sum(total) as sum_total').group('customer')
So i is an array(technically it's not an array, but not important here) containing all the result. So i[0].sum_total will give you the sum of the first customer, but of course you should iterate it to get everything you want.

T-SQL average calculation

I want to incorporate two average calculations for a bunch of value columns in my select statement.
see this link for my simplified table structure including the desired output calculation: Pastebin
1) moving average:
Month1 = value of the value1-column for that month, Month2 = if sum == 0 then write 0, else avg(Month1 and Month2) and so on.
So for each product, I want the moving average for each month within one year.
I have this set up in my Excel but I can't transfer the expression to sql.
2) overall average:
for each product, calculate the average over all years and duplicate the calculated value to all rows for that product.
I hope you can help me out with this. It looks like I need a procedure but maybe it is just a simple statement.
SQL-Server 2012 supports the analytic functions required to do this:
SELECT Product,
Month,
Year,
Value,
AVG_YTD = AVG(Value) OVER(PARTITION BY Year ORDER BY Month),
AVG_Year = AVG(Value) OVER(PARTITION BY Product, Year),
AVG_Overall = AVG(Value) OVER(PARTITION BY Product)
FROM T;
Simplified Example on SQL Fiddle