This question already has answers here:
Calculate a Running Total in SQL Server
(15 answers)
Closed 4 years ago.
I need to create a different column of total sales which is the total of the sales units till that row. As our sales unit will increase, the total sales will increase row by row. I have attached the image to get the clear idea.
Screenshot
One method is use to use of subquery with correlation approach
select *,
(select sum(sales) from table where product = t.product and ? <= t.?) TotalSales
from table t
However, you would required ? (i.e. rowid or id) column that could specify your column ordering.
You can use the following query, which adds up all the sales upto that rowId and for the specific product.
select (select sum(ids)
from TBL_NAME T1
where T1.rowid <= TBL_NAME.rowid and PRODUCT=TBL_NAME.PRODUCT
) as TotalSales
from TBL_NAME;
Following answer is for Oracle DB, you can understand the query and easily convert it to the product you want.
Related
I am working in a task and got stuck at particular question. I am new to SQL so I am reaching out to this platform for the support. Below are the 2 tables. 1st is Theatre_play_table and 2nd is Ticketsales table.
Question: List titles, directors and writers of all shows/plays with the highest total sale.
Theatre_play_table
Ticketsales table
I have pasted screenshot of some part of the table. ID column in both the table represents the same information. Last column in Ticketsales table is Totalamount.
I have tried with below query;
Select theatre_play.title, theatre_play.director, theatre_play.writer, sum(totalamount)
from theatre_play, totalsales
where theatre_play.id = totalsales.id
group by theatre_play.title, theatre_play.director, Theatre_play.writer
order by sum(totalamount) desc
fetch first 3 rows only;
The above approach is not useful when data is huge. I wanted to apply max(sum(totalamount)) but oracle threw an error.
Can anyone please help me solve this question?
If I understand you right, the issue is to get the three highest values?
Then try something like this:
select * from (
Select dpro.title, dpro.director, dpro.writer, sum(fth.totalamount)
from dpro
join fth on dpro.id = fth.id
group by dpro.title, dpro.director, dpro.writer
order by sum(totalamount) desc )
where rownum <=3
This question already has answers here:
Why no windowed functions in where clauses?
(8 answers)
Closed 5 years ago.
I have a table that consists of an order, items on that order, and then the quantity of the item ordered.
What I would like to do is create an additional column for 'Order quantity' which is the sum of item quantities grouped by order (see graphic of table below... order B has 30 total quantity split across three lines)
I can easily accomplish this using sum and partition:
SUM(quantity) OVER (PARTITION BY order_id) order_qty
However, what I need to is then filter to only those orders having quantity > 20. When I try to add that criteria to the WHERE or HAVING clauses, I get this error:
ORA-30483: window functions are not allowed here
One solution appears to be to wrap the whole SQL block inside of another SELECT FROM statement, and then add a WHERE clause to filter by order_qty. Overall that seems sloppy and non-intuitive... Is there a better solution to filter based on an aggregated value that is partitioned at a higher level?
Replace with
SUM(quantity) OVER (PARTITION BY order_id order by 1) order_qty
This question already has answers here:
how to select the most frequently appearing values? [duplicate]
(2 answers)
Closed 9 years ago.
I have a table with column 'Price' and would need to get the most frequent value. What would be the eeasiest way?
One option would be something like
SELECT price
FROM (SELECT price, rank() over (order by cnt desc) rnk
FROM (SELECT price, count(*) cnt
FROM your_table
GROUP BY price))
WHERE rnk = 1
If there are two (or more) prices that occur equally as often, both will be returned by this query. If you want to guarantee a single row, you'll need to tell us how you want to handle ties.
My algorithm is as follows:
Step one: make distinct selection as a collection;
Step two: foreach item in distinct collection count the items found in the original collection as diffcollection;
Step three: select max from diffcollection.
This question already has answers here:
SQL - HAVING vs. WHERE
(9 answers)
Closed 9 years ago.
I am trying to understand the difference between HAVING and WHERE. I understand that HAVING is used with GROUP BY statements. However, I cannot understand why the following statement is accepted:
select SUM(child_id) from children WHERE child_ID = 5 GROUP BY Child_ID
Shouldn't the correct statement be select SUM(child_id) from children GROUP BY Child_ID HAVING child_ID = 5 ?
WHERE clauses are executed before the grouping process has occurred, and only have access to fields in the input table. HAVING is performed after the grouping pocess occurs, and can filter results based on the value of aggregate values computed in the grouping process.
The WHERE clause can be used even if a HAVING is being used. They mean very different things. The way to think about it is as follows:
The WHERE clause acts as a filter at the record level
Anything that gets through is then put into groups specified by your GROUP BY
Then, the HAVING clause filters out groups, based on aggregate (SUM, COUNT,
MIN, etc.) condition
So, if I have a table : ( STORE_ID, STATE_CODE, SALES)
Select STATE, SUM(SALES)
from MyTable
Where SALES > 100
Group By STATE
Having Sum(Sales) > 1000
This will first filter to read only the Store records with Sales over 100. For each Group (by State) it will sum the Sales of only those stores with Sales of 100 or more. Then, it will drop any State unless the State-level summation is more than 1000. [Note: The state summation excludes any store of sales 100 or less.]
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
SQL Query to get latest price
I have a database containing stock price history. I want to select most recent prices for every stock that is listed. I know PostreSQL has a DISTINCT ON statement that would suit ideally here.
Table columns are name, closingPrice and date; name and date together form a unique index.
The easiest (and very uneffective) way is
SELECT * FROM stockPrices s
WHERE s.date =
(SELECT MAX(date) FROM stockPrices si WHERE si.name = s.name);
Much better approach I found is
SELECT *
FROM stockPrices s JOIN (
SELECT name, MAX(date) AS date
FROM stockPrices si
GROUP BY name
) lastEntry ON s.name = lastEntry.name AND s.date = lastEntry.date;
What would be an efficient way to do this? What indexes should I create?
duplicate of:
SQL Query to get latest price
I think that your second approach is very efficient. What's its problem?
You have to add indexes to name and date.