Multiple select statements - Single result - sql

I have a product list view and a v1 value which is used for mapping
For example in erp view it look like below
PRODUCT_ID
PRODUCT_NAME
QUANTITY
v1
1
WOOD PALLET 120x80
10
25
2
WOOD PALLET 200x80
5
25
25
RAW MATERIAL WOOD
100
25
in postgres we have for it 2 tables
Table: PRODUCTS
PRODUCT_ID
PRODUCT_NAME
QUANTITY
1
WOOD PALLET 120x80
10
2
WOOD PALLET 200x80
5
25
RAW MATERIAL WOOD
100
Table: PRODUCTS_MAPPING
PRODUCT_ID
MAPPING_KEY
1
25
2
25
25
25
Now I need a query that will give only one row result which is total of quantity grouped by v1 so result should be 115
I try below query
(
SELECT
SUM( pr.quantity )
FROM
products AS pr
WHERE
pr.product_id = ( SELECT map.product_id FROM products_mapping AS map WHERE mapping_key = v1 )
)
My problem is that after WHERE there is second SELECT statement which is giving multiple results. I need a statement which will do below calculation:
Check v1 value (25)
Go to product mapping table. Find 3 entry for mapping key 25.
Go to Product table and sum quantity for products_id 1,2,3 and give result 10+5+100 = 115

If I understood properly you only want a single result but you haven't put a group by clause in your sentence.
SELECT sum(pr.quantity) FROM products pr JOIN products_mapping map
on pr.product_id=map.product_id WHERE
mapping_key=v1 group by map.mapping_key
I have rewritten your statement using joins.

Related

Return Records that span over two tables in a 1 to many relationship with multiple criteria on the many side

I am trying to get a count of records of data that spans over three tables. I have a table of products, a table of groups and a table showing which groups a product is in. As below:
Product
Product_ID
Product_Name
1
A Product
2
Another Product
Group
Group_ID
Group_Name
10
Group A
20
Group B
30
Group C
40
Group D
Product Grouping
Product_ID
Group_ID
1
10
1
20
1
30
2
20
2
40
3
50
I am trying to write a query that will, given the condition of group ids of say for example (10,20,30), it will return product 1. And if I give group ids of say (20), it will return product 1 and product 2
I have tried:
select * from product_grouping
where group_id = 10 and group_id = 20 and group_id = 30
Use aggregation and having:
select pg.group_id
from product_grouping pg
where pg.group_id in (10, 20 30)
group by product_id
having count(*) = 3;
If the product groupings can be duplicated, use having count(distinct pg.group_id) = 3.

How can I get all rows where just part of a string repeats?

I'm working in SQL (PostgreSQL) with a dataset where each row is a product the company sold and each column contains some information about the product, like price, size, etc. The problem here is that I have a few types of products: (i) products that are only sold outside my state; (ii) products that are sold only inside the state; (iii) products that may be sold both inside or outside the state; (iv) products that are not specified. To specify where the product may be sold, there is extra strings. We use "-IN" if we sell inside the state and "-OUT" if we sell outside the state. Besides this issue, I can't use only split_part() because there might be more than one '-' In other words, I have something like this:
product_name units price
water-out 5 50
water-out 2 20
water-in 3 21
apple-red-in 7 7
ice-out 4 2
wood-out 12 120
leather 17 6
wood-in 1 10
tuna 5 25
it-br-in 1 2
it-br-out 5 25
I want to filter only the products that are sold both inside and outside the state. Products that we have both the possibility of having '-in' and '-out' in the name. I want to get this result:
product_name units price
water-out 5 50
water-out 2 20
water-in 3 21
wood-out 12 120
wood-in 1 10
it-br-in 1 2
it-br-out 5 25
How can I do this?
This answers the original version of the question.
Assuming that the product name has no hyphens and the only suffixes are "-in" and "-out", then split_part() can do this:
select t.*
from t
where exists (select 1
from t t2
where split_part(t2.name, '-', 1) = split_part(t.name, '-', 1) and
t2.name <> t.name
)
Here is a db<>fiddle.

Select TOP 2 maximum values in SQL

I neet to select TOP 2 products with Max Price.
ProductID ProductName SupplierID CategoryID Unit Price
1 Chais 1 1 10 bags 18
2 Chang 1 1 24 bottles 19
3 Aniseed Syrup 1 2 12 bottles 10
I have used:
Select TOP 2 *
from Products
where Price = (Select Max(Price) from Products);
But the result is just 1 row.
This will give you the top 2 max prices but if the same price is in there twice you would get the same value twice, but from your code above that is what it would do so assuming that is what you are looking for.
Select TOP 2 * from Products order by Price DESC
You need order by clause :
select top (2) *
from Products p
order by price desc;

SQL: Getting Duplicate Data When Attempting to Sum and Join 2 Tables

In Essence, I have two tables (purchases and sales) that I need to join together. Both tables have different Primary Keys, but they share the same foreign key. Every time a purchase is made, a new entry is made (with it's own primary key). Every time a sale is made, a new entry is made (with its own key).
Summary of Used Tables:
Purchase Data
Individual Product Cost (AS IPC)
Sales Tax (AS ST)
Quantity (AS Q)
SKU (Foreign Key)
Primary Key (AS PK)
Sales
Amount Sold (AS AS)
Total (AS T)
SSKU(Foreign Key)
Primary Key (AS PK)
When I attempt to Sum and Join the data based on the product I get weird results.
Purchase Table Data:
SKU | IPC | ST | Q | PK
1 2.40 .02 5 1
2 5.00 .05 20 2
3 4.00 .04 5 3
1 5.00 .04 20 4
Sales Table:
SSKU | T | AS | PK
1 10 2 1
2 9 1 2
3 9 4 3
1 9 1 4
2 9 2 5
1 9 2 6
1 9 4 7
Expected Results
SKU | (IPC + ST)Q | Q | SUM AS | SUM T
1 354.9 25 9 37
2 101 20 3 9
3 80.8 5 4 18
When trying the script creator in OpenOffice Base, It would give me the expected results for product 3, but it would be wrong for products 1 and 2.
I read up on SQL programming, and attempted my hand at it. I THINK this would solve the issue by summing the two tables separately before merging. Instead, I keep receiving an error now, and I can't find the mistake.
Current Code:
SELECT
"A"."SKU"
,SUM(( "A"."Individual Product Cost" + "A"."Sales Tax" ) * "A"."Quantity")
,"A"."Quantity"
,"D"."Sales"
,"D"."Sold"
FROM "PurchaseData" AS "A"
Inner Join
(
Select
"ACT"."SSKU"
,SUM("ACT"."Amount Sold") AS Sold
,SUM("ACT"."Total") AS Sales
From
"Sales" AS ACT
GROUP BY
"ACT"."SSKU"
)
AS D
on "A"."SKU" = "D"."SSKU"
Group By
"A"."SKU"
EDIT:
According to a random online Syntax checker, it's line 3 (I don't see it).
According to Openoffice Base:
SQL Status: HY000
Error code: 1000
syntax error, unexpected $end, expecting BETWEEN or IN or SQL_TOKEN_LIKE
Thanks to Jayvee, I got it working!
Select
"A"."SKU"
,"B"."Sold"
,"B"."Sales"
,"A"."Total Cost"
,"A"."Total Purchased"
From
-- First Sub Query --
(
Select
"PD"."SKU" As SKU
,SUM(( "PD"."Individual Product Cost" + "PD"."Sales Tax" ) *"PD"."Quantity") AS "Total Cost"
,SUM ("PD"."Quantity") AS "Total Purchased"
From
"PurchaseData" AS PD
GROUP BY
"PD"."SKU"
)
As A
--End First--
Join
--Start 2nd--
(
Select
"ACT"."SSKU" AS ASKU
,SUM("ACT"."Amount Sold") AS Sold
,SUM("ACT"."Total") AS Sales
From
"Sales" As ACT
GROUP BY
"ACT"."SSKU"
)
As B
--End 2nd--
On
"B"."ASKU" = "A"."SKU"
you can sum purchase data in a subquery, the same as you did with sales, and then join both subqueries without aggregation:
Select
"A"."SKU"
,"B"."Sold"
,"B"."Sales"
,"A"."Total Cost"
,"A"."Total Purchased"
From
-- First Sub Query --
(
Select
"PD"."SKU" As SKU
,SUM(( "PD"."Individual Product Cost" + "PD"."Sales Tax" ) *"PD"."Quantity") AS "Total Cost"
,SUM ("PD"."Quantity") AS "Total Purchased"
From
"PurchaseData" AS PD
GROUP BY
"PD"."SKU"
)
As A
--End First--
Join
--Start 2nd--
(
Select
"ACT"."SSKU" AS ASKU
,SUM("ACT"."Amount Sold") AS Sold
,SUM("ACT"."Total") AS Sales
From
"Sales" As ACT
GROUP BY
"ACT"."SSKU"
)
As B
--End 2nd--
On
"B"."ASKU" = "A"."SKU"

How to use subquery to populate column in Access query

I am working on an Access database which is used for forecasting purchases and I am trying to create a query in which would give me list of records with valid prices and row sums.
I am running into problems when I try to combine prices to quantities. I have following tables
Table that contains forecasting data (columns not relevant for this query omitted)
need_rows
ID product_id qty use_date
----------------------------
1 1 100 1.1.2014
2 1 50 15.1.2014
...
And table for prices
prices
ID product_id price valid_from
----------------------------------
1 1 1 1.12.2013
2 1 2 24.12.2013
3 1 5 10.1.2014
...
Query resulst should be something like below:
result of query
product_id use_date qty price sum
---------------------------------------
1 1.1.2014 100 2 200
1 15.1.2014 50 5 250
...
Meaning that I need to fetch valid price to each of the rows based on the use_date from need_rows and valid_from date from prices. Valid prices is the one that has valid_from date equal or most recent to use_date.
Below is one of the approaches I have tried with no luck.
SELECT prices.price
FROM prices
WHERE (((prices.product_id)=[product_id]) AND ((prices.valid_from)=
(SELECT Max(prices.valid_from) AS valid
FROM prices
WHERE (((prices.product_id)=[product_id]) AND ((prices.valid_from)<=[use_date]));).));
Any help is appreciated!
SELECT need_rows.Id
, need_rows.qty
, need_rows.product_id
, (SELECT TOP 1 price
FROM prices
WHERE need_rows.product_id = prices.product_id
AND need_rows.use_date >= prices.valid_from
ORDER BY prices.valid_from DESC) AS currentprice
FROM need_rows;