SQL treat two entries as one - sql

I have a table with stock codes and quantity sold, but I would like to treat 2 different stock codes as one, the reason being is that one is imported and the other one locally produced but are the same product,
lets say
Product A - Imported, Stock code is abc123
Product A - Local, Stock code is aimp563
I want to sum over the quantity sold but treat the same product with and an imported stock code and local stock code as one. Is this possible?
Okay this is what I have
tbe table looks like
Product | StockCode | QtySold
Product A - Local | prdA001loc | 100
Product A - Imported | prdAImp7Z4 | 150
SELECT Product, SUM(QtySold) FROM tblA GROUP BY StockCode, Product
But this will just return the table as is. I would like this output:
Product | QtySold
Product A | 250

I believe that you need to update your DB schema to have reflect this information however if you need some naive solution you can use the following statement
SELECT substring(product, 1 , charindex('-',product)), SUM(QtySold)
FROM tblA GROUP BY substring(product, 1 , charindex('-',product))
note that the above statement assuming that all your products name will be similar to what is mentioned inside your question

Related

POSTGRESQL - Finding specific product when

I've attempted to write a query but I've not managed to get it working correctly.
I'm attempting to retrieve where a specific product has been bought but where it also has been bought with other products. In the case below, I want to find where product A01 has been bought but also when it was bought with other products.
Data (extracted from tables for illustration):
Order | Product
123456 | A01
123457 | A01
123457 | B02
123458 | C03
123459 | A01
123459 | C03
Query which will return all orders with product A01 without showing other products:
SELECT
O.NUMBER
O.DATE
P.NUMBER
FROM
ORDERS O
JOIN PRODUCTS P on P.ID = O.ID
WHERE
P.NUMBER = 'A01'
I've tried to create a sub query which brings back just orders of product A01 but I don't know how to place it in the query for it to return all orders containing product A01 as well as any other product ordered with it.
Any help on this would be very grateful.
Thanks in advance.
You can use conditional SUM to detect if one ORDER group have one ore more 'A01'
CREATE TABLE orders
("Order" int, "Product" varchar(3))
;
INSERT INTO orders
("Order", "Product")
VALUES
(123456, 'A01'),
(123457, 'A01'),
(123457, 'B02'),
(123458, 'C03'),
(123459, 'A01'),
(123459, 'C03')
;
SELECT "Order"
FROM orders
GROUP BY "Order"
HAVING SUM(CASE WHEN "Product" = 'A01' THEN 1 ELSE 0 END) > 0
I appreciated Juan's including the DDL to create the database on my system. By the time I saw it, I'd already done all the same work, except that I got around the reserved word problem by naming that field Order1.
Sadly, I didn't consider that either of the offered queries worked on my system. I used MySQL.
The first one returned the A01 lines of the two orders on which other products were ordered too. I took Alex's purpose to include seeing all items of all orders that included A01. (Perhaps he wants to tell future customers what other products other customers have ordered with A01, and generate sales that way.)
The second one returned the three A01 lines.
Maybe Alex wants:
select *
from orders
where Order1 in (select Order1
from orders
where Product = 'A01')
It outputs all lines of all orders that include A01. The subquery makes a list of all orders with A01. The first query returns all lines of those orders.
In a big database, you might not want to run two queries, but this is the only way I see to get the result I understood Alex wanted. If that is what he wanted, he would have to run a second query once armed with output from the queries offered, so there's no real gain.
Good discussion. Thanks to all!
Use GROUP BY clause along with HAVING like
select "order", Product
from data
group by "order"
having count(distinct product) > 1;

DB2 Select from two tables when one table requires sum

In a DB2 Database, I want to do the following simple mathematics using a SQL query:
AvailableStock = SupplyStock - DemandStock
SupplyStock is stored in 1 table in 1 row, let's call this table the Supply table.
So the Supply table has this data:
ProductID | SupplyStock
---------------------
109 10
244 7 edit: exclude this product from the search
DemandStock is stored in a separate table Demand, where demand is logged as each customer logs demand during a customer order journey. Example data from the Demand table:
ProductID | DemandStock
------------------------
109 1
244 4 edit: exclude this product
109 6
109 2
So in our heads, if I want to calculate the AvailableStock for product '109', Supply is 10, Demand for product 109 totals to 9, and so Available stock is 1.
How do I do this in one select query in DB2 SQL?
The knowledge I have so far of some of the imagined steps in PseudoCode:
I select SupplyStock where product ID = '109'
I select sum(DemandStock) where product ID = '109'
I subtract SupplyStock from DemandStock
I present this as a resulting AvailableStock
The results will look like this:
Product ID | AvailableStock
109 9
I'd love to get this selected in one SQL select query.
Edit: I've since received an answer (that was almost perfect) and realised the question missed out some information.
This information:
We need to exclude data from products we don't want to select data for, and we also need to specifically select product 109.
My apologies, this was omitted from the original question.
I've since added a 'where' to select the product and this works for me. But for future sake, perhaps the answer should include this information too.
You do this using a join to bring the tables together and group by to aggregate the results of the join:
select s.ProductId, s.SupplyStock, sum(d.DemandStock),
(s.SupplyStock - sum(d.DemandStock)) as Available
from Supply s left join
Demand d
on s.ProductId = d.ProductId
where s.ProductId = 109
group by s.ProductId, s.SupplyStock;

Find Count Distinct in CakePHP

This is a simple query problem. But it seems that I can't get it right :(
I just started using cakephp last week. I'm still playing around exploring. Anyway, here's my problem.
This is the relationship in Model: Product has many Stock. Stock belongs to Product.
This is the sample STOCKS table:
ID | Product Name | Transaction
------------------------------------
1 | Astringent | Purchase
2 | Glutathione | Sales
3 | Glutathione | Sales
I would like to get the number of transaction per product from the STOCKS table.
This is the output I would like with distinct product name:
Transaction | Astringent | Glutathione
--------------------------------------------
purchase | 1 | 0
sales | 0 | 2
Here is a sql query- for exactly what you requested.
SELECT transaction,
SUM(
CASE
WHEN product_name = 'Astringent' THEN 1
ELSE 0
END) AS 'Astringent',
SUM(
CASE
WHEN product_name = 'Glutathione' THEN 1
ELSE 0
END) AS 'Glutathione'
FROM stock
GROUP BY transaction;
However, are you looking for a pivot table i.e., an output with a variable number of columns based on a random number of products? If so, your solution is lot more complicated as a MySQL query, and potentially less complicated as a MySQL and PHP solution. In either case, I think you should share more of your database schema / CakePHP model along with some controller information. In order to render a view with this table is not overly difficult as long as you want Cakephp to output this format.

SQL - calculate consumption of materials based on recipe

I'm not sure how to ask my question, so I'll explain what I'm trying to do: I'm building an app in Delphi XE, which should calculate the consumption of raw materials, based on products recipes and orders.
I have 5 tables: Orders, OrdersContent, Products, Raw Materials and Recipes. Each order is composed of a few products, and each product has it's own recipe of raw materials.
I already summed up all products from all orders using sql in Query1.
This is the command for Query1:
select Products.Price,
OrdersContent.ID_Product, sum(OrdersContent.QNT) as QNT_Sum,
(Products.Price * sum(OrdersContent.QNT)) as Value
from Orders, OrdersContent, Products
where Orders.ID = OrdersContent.ID_Order
and Products.ID = OrdersContent.ID_Product
group by
OrdersContent.ID_Product, Products.Price
This returns:
|Price | ID_Product | QNT_Sum | Value |
----------------------------------------
| 2 | 122521 | 150 | 300 |
| 10 | 366547 | 10 | 100 |
| xxx | xxxxxx | xxx | xxxxx|
It's exactly what I want.
So now I'm wondering if there's a way to calculate the raw materials consumption also using sql, as the only other way I know how to do this is to iterate through the whole Query1 and calculate raw materials consumption for each record(product) individually, add it to a new table and then sum up the results, which is very time consuming.
I'm pretty sure there must be a more efficient way to do this, but have no clue as to how or where to search how to do it. I'm not asking for the code, but some pointers or links to tutorials or examples.
I hope I'm clear enough, if not please do ask for more info.
Add Raw Materials and Recipe to your FROM clause with the appropriate joins. Group by raw materials. Remove id_product and price from your group by statement. Change the aggregation in your select to sum(products.price*orderscontent.qnt).
I'm guessing at your column names in Recipes and Raw Materials but here's the general idea.
select Recipes.ID_RAW_MATERIALS,
sum(OrdersContent.QNT) as QNT_Sum,
sum(Products.Price * OrdersContent.QN)) as Value
from Orders, OrdersContent, Products, Recipes, RawMaterials
where Orders.ID = OrdersContent.ID_Order
and Products.ID = OrdersContent.ID_Product
and Recipes.ID_PRODUCT = Products.ID
AND Recipes.ID_RAW_MATERIAL = Rawmaterials.ID
group by Recipes.ID_RAW_MATERIALS

Rails Select and Group by summation Custom SQL Calls

I have a table named sales, which has the following fields:
id (integer)
quantity (integer)
product_id (integer)
payment_method (string - bad I know)
I want to hook these records up to the google visualization api but first I need to actually get the data presentable in the way that I want. The google visualization integration is not the issue. What IS the issue is that I can't seem to get the group() function or select() function to do what I want.
I'm not sure that group is what I want, but basically I would like to do a sales totals per product by payment_method.
My original idea was that it would look like
.select("SUM(quantity) as total_sold", :product_id).group(:payment_method)
But that doesn't really help me sort them by product. What I'd like the data to look like would be:
CASH SALES:
Product A: 103 sales
Product B: 32 sales
Product C: 87 sales
CREDITCARD SALES:
Product A: 23 sales
Product B: 43 sales
Product C: 12 sales
DONATION SALES:
Product A: # sales
Product B: 43 sales
Product C: 12 sales
Any help would be appreciated!
.select("SUM(quantity) as total_sold", :product_id).group(:payment_method, :product_id)
Here first it will group the result set by payment method, then by product id.
Keep the select of all columns inside of one string. Generated SQL will use that "as is". No need to close the string and put 2nd parameter as symbol :product_id in select.
Important to add all columns from group by in select also.
Consider .order("payment_method, product_id") also.
.select("SUM(quantity) as total_sold, payment_method, product_id").group(:payment_method, :product_id)
Tested using rails console:
Product.select("product_line_id, public_product_id pp_id, count(product_id) num_products") .group("product_line_id, public_product_id").map{|p| "Public Prod Id: #{p.pp_id} has #{p.num_products} products " }
Product Load (0.2ms) SELECT public_product_id pp_id, count(product_id) num_products FROM products GROUP BY products.public_product_id
=> [
"Public Prod Id: 5 has 1 products ",
"Public Prod Id: 6 has 2 products ",
"Public Prod Id: 8 has 1 products ", ... ]