Sum nr of sales on a typical article number SQL - sql

it's pretty simple i guess but i can't get it to work.
I have a Sales table with theese columns
Date,Artnr,Amount
For example
20150326, 19929, 2
20150326, 10231, 1
20150326, 10001, 3
20150325, 19929, 4
Now i want to make a SQL that gives me the Artnr and the sum Amount back.So in the example above i sold 6 artnr 19929 at two different times. Now i want to sum the amount on the rows with the same artnr and add them togheter. Like this.
10231, 1
10001, 3
19929, 6
The closest i get is with this SQL
SELECT a.artnr (SELECT SUM(b.amount) FROM SALES b WHERE b.artnr = a.artnr)
FROM SALES a
My Problem here is that i still get all rows back but at least it gives me the right sum amount.
19929, 6
10231, 1
10001, 3
19929, 6
Can someone help me with this please.

Just use group by:
SELECT artnr, SUM(amount)
FROM SALES s
GROUP BY artnr;

Related

Grouping and Summing Totals in a Joined Table

I have two tables Medication and Inventory. I'm trying to SELECT all the below details from both tables but there are multiple listings of medication ids with different BRANCH_NO also in the INVENTORY table (the primary key in INVENTORY is actually BRANCH_NO, MEDICATION_ID composite key)
I need to total up the various medication_IDs and also join the tables in one SELECT command and display all the infomation for each med (there are 5) with a total sum of each med at the end of each row. But im getting all muddled trying Group by and Sum and at one point partition. Help please I'm new to this.
Below is the latest non working version - but it doesn't display
Medication Name
Medication Desc
Manufacturer
Pack Size
like i chanced it might.
SELECT I.MEDICATION_ID,
SUM(I.STOCK_LEVEL)
FROM INVENTORY I
INNER JOIN (SELECT MEDICATION_NAME, SUBSTR(MEDICATION_DESC,1,20) "Medication Description",
MANUFACTURER, PACK_SIZE FROM MEDICATION) M ON MEDICATION_ID=I.MEDICATION_ID
GROUP BY I.MEDICATION_ID;
For the data imagine I want this sort of output:
MEDICATION_ID MEDICATION_NAME STOCK_LEVEL OtherColumns.....
1 Alpha 10
2 Bravo 20
3 Charlie 20
1 Alpha 30
4 Delta 10
5 Echo 20
5 Echo 40
2 Bravo 10
grouping and totalling into this:
MEDICATION_ID MEDICATION_NAME STOCK_LEVEL OtherColumns.....
1 Alpha 40
2 Bravo 30
3 Charlie 20
4 Delta 10
5 Echo 60
I can get this when its just one table but when Im trying to join tables and also SELECT things its just not working.
Thanks in advance guys. I appreciate it may be a simple solution, but it will be a big help.
You need to write explicitly all non-aggregated columns into both SELECT and GROUP BY lists ( Btw, no need to use a nested query, and if it's the case MEDICATION_ID column is missing in it ) :
SELECT I.MEDICATION_ID, M.MEDICATION_NAME, SUM(I.STOCK_LEVEL) AS STOCK_LEVEL,
SUBSTR(M.MEDICATION_DESC,1,20) "Medication Description", M.MANUFACTURER, M.PACK_SIZE
FROM INVENTORY I
JOIN MEDICATION M ON M.MEDICATION_ID = I.MEDICATION_ID
GROUP BY I.MEDICATION_ID, M.MEDICATION_NAME, SUBSTR(M.MEDICATION_DESC,1,20),
M.MANUFACTURER, M.PACK_SIZE;
This way, you'll be able to return all the listed columns.

Possible to keep fraction in a query?

I am looking for a way to add up averages in SQL. Here is an example of the data I have:
product avg_price
phone 104.28
car 1000.00
And I'm looking to build something like this:
product avg_price
[all] 544.27
phone 104.28
car 1000.00
The way I'm currently doing it is to store the count and sum in two different columns, such as:
product cnt total
phone 203 20,304.32
car 404 304,323.30
And from that get the average. However, I was wondering if it is possible in SQL to just 'keep the fraction' and be able to add them as needed. For example:
product avg_price
[all] [add the fractions]
phone 20,304.32 / 203
car 304,323.30 / 404
Or do I need to use two columns in order to get an average of multiple aggregated rows?
You don't need 2 columns to get the average, but if you want to display as a fraction then you will need both numbers. They don't need to be in 2 columns though.
select product, sum(total) ||'/'||sum(count)
from table a
join table b on a.product=b.product
union
select product, total ||'/'||count
from table a
join table b on a.product=b.product;

Total Sum SQL Server

I have a query that collects many different columns, and I want to include a column that sums the price of every component in an order. Right now, I already have a column that simply shows the price of every component of an order, but I am not sure how to create this new column.
I would think that the code would go something like this, but I am not really clear on what an aggregate function is or why I get an error regarding the aggregate function when I try to run this code.
SELECT ID, Location, Price, (SUM(PriceDescription) FROM table GROUP BY ID WHERE PriceDescription LIKE 'Cost.%' AS Summary)
FROM table
When I say each component, I mean that every ID I have has many different items that make up the general price. I only want to find out how much money I spend on my supplies that I need for my pressure washers which is why I said `Where PriceDescription LIKE 'Cost.%'
To further explain, I have receipts of every customer I've worked with and in these receipts I write down my cost for the soap that I use and the tools for the pressure washer that I rent. I label all of these with 'Cost.' so it looks like (Cost.Water), (Cost.Soap), (Cost.Gas), (Cost.Tools) and I would like it so for Order 1 it there's a column that sums all the Cost._ prices for the order and for Order 2 it sums all the Cost._ prices for that order. I should also mention that each Order does not have the same number of Costs (sometimes when I use my power washer I might not have to buy gas and occasionally soap).
I hope this makes sense, if not please let me know how I can explain further.
`ID Location Price PriceDescription
1 Park 10 Cost.Water
1 Park 8 Cost.Gas
1 Park 11 Cost.Soap
2 Tom 20 Cost.Water
2 Tom 6 Cost.Soap
3 Matt 15 Cost.Tools
3 Matt 15 Cost.Gas
3 Matt 21 Cost.Tools
4 College 32 Cost.Gas
4 College 22 Cost.Water
4 College 11 Cost.Tools`
I would like for my query to create a column like such
`ID Location Price Summary
1 Park 10 29
1 Park 8
1 Park 11
2 Tom 20 26
2 Tom 6
3 Matt 15 51
3 Matt 15
3 Matt 21
4 College 32 65
4 College 22
4 College 11 `
But if the 'Summary' was printed on every line instead of just at the top one, that would be okay too.
You just require sum(Price) over(Partition by Location) will give total sum as below:
SELECT ID, Location, Price, SUM(Price) over(Partition by Location) AS Summed_Price
FROM yourtable
WHERE PriceDescription LIKE 'Cost.%'
First, if your Price column really contains values that match 'Cost.%', then you can not apply SUM() over it. SUM() expects a number (e.g. INT, FLOAT, REAL or DECIMAL). If it is text then you need to explicitly convert it to a number by adding a CAST or CONVERT clause inside the SUM() call.
Second, your query syntax is wrong: you need GROUP BY, and the SELECT fields are not specified correctly. And you want to SUM() the Price field, not the PriceDescription field (which you can't even sum as I explained)
Assuming that Price is numeric (see my first remark), then this is how it can be done:
SELECT ID
, Location
, Price
, (SELECT SUM(Price)
FROM table
WHERE ID = T1.ID AND Location = T1.Location
) AS Summed_Price
FROM table AS T1
to get exact result like posted in question
Select
T.ID,
T.Location,
T.Price,
CASE WHEN (R) = 1 then RN ELSE NULL END Summary
from (
select
ID,
Location,
Price ,
SUM(Price)OVER(PARTITION BY Location)RN,
ROW_number()OVER(PARTITION BY Location ORDER BY ID )R
from Table
)T
order by T.ID

Finding the sum of sales when a series of conditions are met

I have a database table that looks like below. It contains a key (id) that identified each transaction. Within each transaction, there may be multiple items that were purchased, thus someome with transact 103 has three different id values because they purchased three different items.
Here is what I am trying to do. For a given set of conditions, I want to total number of items that were purchased (item qty). Let's say that my conditions are that for stores 20 and 35, AND items 7, 12, aned 21, I want to find the total number of purchased items (item qty). When condition x is met, which is the reason for the subquery, sun up the item quantity to get total sales.
Can anyone help?
transac id item_qty store item
101 1 2 20 13
102 2 1 35 21
103 3 3 35 16
103 4 1 35 12
103 5 1 35 7
104 6 1 15 21
104 7 2 20 7
I have the following query which is related to my example but when I utilize such queries on my data it returns a null value each time.
SELECT SUM(Cnt) AS "Sales Count"
FROM (SELECT ti.id, SUM(ti.item_qty) AS Cnt
FROM dbo.vTransactions1 ti
WHERE ti.store IN (20, 35)
AND ti.item IN (7, 12, 21)
GROUP BY ti.id) inner_query1;
One way of doing this would be to group by store and item and then calculating the sum. This way you would be able to add more conditions if required based on valid combinations of (Store,Item). You have grouped by id which is not worth as each row will have unique id so no group will be formed.
For given condition you can write as;
;with CTE as
(
select sum(item_qty) as Cnt,store,item
from test
group by store,item
)
select sum (Cnt) as [Sales Count]
from CTE
where store in (20,35)
and item in (7,12,21))
SQL Fiddle Demo here.
I have no idea why there is a subquery here. Unless I'm missing something, this should work:
select sum (item_qty)
FROM dbo.vTransactions1 ti
WHERE ti.store IN (20, 35)
AND ti.item IN (7, 12, 21)
If you need to add extra conditions in the outer query - you either need to
remove the "Sum" from Sum(Cnt) as the Sum is already done in the sub query (and probably return the ID as well); OR
You need to add GROUP BY condition to the outer query as well.

Omit item from Sum SQL

I'm very new to programming and SQL, I can't figure this one out, perhaps I haven't learned the concept yet, but I'm hoping you can help me. Sorry if it's too easy and boring.
/*2.37 Write an SQL statement to display the WarehouseID and the sum of
QuantityOnHand,grouped by WarehouseID. Omit all SKU items that have 3 or more items
on hand from the sum, and name the sum TotalItemsOnHandLT3 and display the results
in descending order of TotalItemsOnHandLT3.*/
SELECT WarehouseID, SUM(QuantityOnHand) AS TotalItemsOnHandLT3
FROM INVENTORY
GROUP BY WarehouseID
HAVING COUNT(WarehouseID) >= 3
ORDER BY TotalItemsOnHandLT3 DESC
"Omit all SKU items that have 3 or more items on hand from the sum", sounds more like :
FROM INVENTORY WHERE QuantitiyOnHand < 3
rather than :
HAVING COUNT(WarehouseID) >= 3
INVENTORY is the list of products (SKU = Stock Keeping Unit = Individual Product Stored in the warehouse) where every product has a WarehouseID. This warehouseID presumably determines where the product is stored.
By Omit all SKU items, it asks you to only display those products that are stored in minimum 3 places in the warehouse. This can be done with the having clause,
HAVING COUNT(WarehouseID) >= 3
I do not know the structure and data of your INVENTORY table, but simply put, Consider your data is like this:
SKUID WareHouseID QuantityOnHand
1 1 10
1 2 10
2 1 10
1 3 5
2 2 20
In the above case, Product = 1 (SKUID), is stored in 3 different warehouses whereas product 2 is stored in 2 warehouses. Hence,
SKUID COUNT(WareHouseID) SUM(QuantityOnHand)
1 3 25
2 2 30
In this case, your query will only "Omit" product 1, and not the product 2.
Its says Omit, they why
HAVING COUNT(WarehouseID) >= 3
and not
HAVING COUNT(WarehouseID) < 3