Get the Selected Minimum Price Row's Columns in SQL? - sql

I have the following query,
SELECT * FROM Products P
OUTER APPLY
(
SELECT COALESCE(CP.NewPrice, CP.Price, 2147483647) AS MinimumChildPrice
--,SelectedMinimumPriceRow.Promotion
FROM Products CP
WHERE CP.ParentID = P.ID
) AS C
The problem is SelectedMinimumPriceRow.Promotion. I need to select this extra Promotion column of selected Minimum Price/NewPrice?
For example if I have,
ID ParentID Promotion Price NewPrice
----------------------------------------
1 NULL a 81 52
2 1 b 11 81
3 1 c 91 14
4 1 d 11 25
5 1 e 10 61
For ID=1, the minimum price will be 14. So, I need to select c as well.

You could simply replace your OUTER APPLY query with a TOP 1 query ordering by price, that will allow you to grab any column;
SELECT * FROM Products P
OUTER APPLY
(
SELECT TOP 1 COALESCE(CP.NewPrice, CP.Price, 2147483647) MinimumChildPrice,
promotion MinimumChildPricePromotion
FROM Products CP
WHERE CP.ParentID = P.ID
ORDER BY COALESCE(CP.NewPrice, CP.Price, 2147483647)
) AS C
An SQLfiddle to test with.

Related

Group by having count less than n or null should return true

I want this query to return 1 also in the case when no record exists. With a count less than 2 or even if no records exist it should return 1.
SELECT 1
FROM dbo.Product BS
WHERE BS.ASIN = '072142452X'
GROUP BY ASIN
HAVING COUNT(1) < 2
The result should be 1 in the case when no record exists in the table.
List of All Products In table
Product
Id ASIN
1 12A
2 12B
3 1AC
4 123
5 12D
List of Accounts
Account
Id Name
1 A
2 B
3 C
Now Listing happens in various accounts
List of products Listed in various accounts (Product Id and Account combination is unique. Means one product will be listed in one account only once)
ProductListing
Id ProductId AccountId
1 2 1
2 1 1
3 4 1
4 2 2
5 4 2
6 5 3
I want if a product is already listed in one account or in two different accounts it should not come in my query of listing product
Query of Listing product in Account 3. So products which are already listed in 3 and in more than 2 accounts should not come
Select P.Id, P.ASIN
FROM dbo.Product P
WHERE NOT EXISTS (
SELECT 1
FROM dbo.ProductListing PL
WHERE P.Id = PL.ProductId AND AccountId = 3
) AND EXISTS (
SELECT 1
FROM dbo.ProductListing PL
WHERE P.Id = PL.ProductId
GROUP BY PL.ProductId
HAVING COUNT(1) < 2
)
You can use a CASE expression on the number of rows returned as follows.
DECLARE #Asin varchar(10) = '072142452X';
SELECT
CASE WHEN (
SELECT COUNT(*)
FROM dbo.Product BS
WHERE BS.[ASIN] = #Asin
) < 2 THEN 1 ELSE 0 END;
Note: there is no reason to GROUP BY when you are already filtering down to 1 ASIN.
Based on your edit you can modify your query to use the same sub-query as I have already show as follows:
SELECT P.Id, P.[ASIN]
FROM dbo.Product P
WHERE NOT EXISTS (
SELECT 1
FROM dbo.ProductListing PL
WHERE PL.ProductId = P.Id AND AccountId = 3
) AND (
SELECT COUNT(*)
FROM dbo.ProductListing PL
WHERE PL.ProductId = P.Id
) < 2;
Drop your GROUP BY line.
Consider how this will always give a row:
SELECT COUNT(1)
FROM dbo.Product BS
WHERE BS.ASIN = '072142452X'
But GROUP BY means you return a row per group, and you don't have any groups because you're filtering out the rows that would've made one.
So this is what you want.
SELECT 1
FROM dbo.Product BS
WHERE BS.ASIN = '072142452X'
Having Count(1) < 2
ADDENDUM: I wrote it this way because it's the closest to the OP's original form. But another option, which doesn't get caught up in the nuances of GROUP BY and HAVING is:
SELECT 1
WHERE (
SELECT COUNT(1)
FROM dbo.Product BS
WHERE BS.[ASIN] = '072142452X'
) < 2

Sql update table with joined sums of other tables

I'm trying to reduce storage with packages included in sold products.
Products can have different amounts of same packages and invoice can have different amounts of products in separate lines. Action should be performed against certain invoiceID.
Simplified tables (summary is not column, just added to ease up calculation):
Inv_rows
InvID ProdID Qty *Summary*
999 100 2 *100 = 10*
999 101 2 *101 = 2*
999 102 2 *102 = 2*
999 103 2 *103 = 10*
999 100 8
999 103 8
Pack_to_prod
ProdID PackID Qty
100 A 2 *A = 20*
100 B 1 *B = 10*
101 A 1 *A = 2*
101 B 1 *B = 2*
102 A 3 *A = 6*
103 B 2 *B = 20*
Storage
ItemID Qty
A 100 *A = 28*
B 100 *B = 32*
**Desired Result**
Storage
ItemID Qty
A 72 *(100-28)*
B 68 *(100-32)*
What I have tried is:
UPDATE Storage
SET Storage.Qty = Storage.Qty -
(SELECT SUM (Inv_rows.Qty * Pack_to_prod.Qty) FROM Inv_rows
WHERE Inv_rows.ProdID IN (SELECT ProdID FROM Pack_to_prod
WHERE Pack_to_prod.PackID=Storage.ItemID) AND Inv_rows.InvId = 999
)
FROM Inv_rows, Storage, Pack_to_prod
WHERE Inv_rows.ProdID = Pack_to_prod.ProdID
AND Pack_to_prod.PackID = Storage.ItemID
AND Inv_rows.InvID = 999
But the problem is the 'IN' since it doesn't match the rows but I can't use '=' as 'where' results more than one line.
Then I tried to simplify it for myself (as I'm not a professional) with a select clause to understand what exactly needs to be done..
SELECT
Pack_to_prod.PackID AS PackageID,
Inv_rows.ProdID AS ProductID,
Inv_rows.Qty AS ProductQty,
Pack_to_prod.Qty AS PackageQtyPerProduct,
Inv_rows.Qty*Pack_to_prod.Qty AS PackageTotal,
Storage.Qty AS StorageQty,
Storage.Qty - (Inv_rows.Qty * Pack_to_prod.Qty) AS NewStorageQty
FROM Pack_to_prod,Inv_rows,Storage
WHERE Inv_rows.ProdID = Pack_to_prod.ProdID
AND Pack_to_prod.PackID = Storage.ItemID
AND Inv_rows.InvID = 999
GROUP BY Inv_rows.ProdID, Pack_to_prod.PackID, Pack_to_prod.Qty, Storage.Qty, Inv_rows.Qty
Which results as simple list showing the problem why they can't be just summed up:
PackageID ProductID ProductQty PackageQtyPerProduct PackageTotal StorageQty NewStorageQty
A 100 2 2 4 100 96
A 100 8 2 16 100 84
B 100 2 1 2 100 98
B 100 8 1 8 100 92
A 101 2 1 2 100 98
B 101 2 1 2 100 98
A 102 2 3 6 100 94
B 103 2 2 4 100 96
B 103 8 2 16 100 84
But can't figure out how to make it run 'line by line' so that each 'Pack_to_prod.Qty' would be handled separately.
Any help in right direction appreciated.
This seems like some aggregations and joins. To get the changes in values, then:
select pp.packid, sum(p.qty * pp.qty) as new_qty
from (select ir.prodid, sum(qty) as qty
from inv_rows ir
group by ir.prodid
) p join
Pack_to_prod pp
on pp.prodid = p.prodid
group by pp.packid;
You can then use this in an update:
update s
set s.qty = s.qty - pp.new_qty
from storage s join
(select pp.packid, sum(p.qty * pp.qty) as new_qty
from (select ir.prodid, sum(qty) as qty
from inv_rows ir
group by ir.prodid
) p join
Pack_to_prod pp
on pp.prodid = p.prodid
group by pp.packid
) pp
on pp.packid = s.itemid;
This was explained very well. The SQL code is user older coding conventions (such as JOIN conditions in the WHERE clause, instead of FROM) and isn't organized into subqueries properly. All the pieces are present though. I think something like this is what you're looking for.
with
inv_cte(ProdID, sum_qty) as (
select ProdID, sum(Qty)
from Inv_rows
group by ProdID),
pack_cte(PackID, prod_qty) as (
select pp.PackID, sum(pp.Qty*ic.sum_qty)
from Pack_to_prod pp
join inv_cte ic on pp.ProdID=ic.ProdID
group by pp.PackID)
select s.ItemID, s.Qty-p.prod_qty as ResultQty
from Storage s
join pack_cte p on s.ItemID=p.PackID;
Update statement
with
inv_cte(ProdID, sum_qty) as (
select ProdID, sum(Qty)
from Inv_rows
group by ProdID),
pack_cte(PackID, prod_qty) as (
select pp.PackID, sum(pp.Qty*ic.sum_qty)
from Pack_to_prod pp
join inv_cte ic on pp.ProdID=ic.ProdID
group by pp.PackID)
update s
set Qty=Qty-p.prod_qty
from Storage s
join pack_cte p on s.ItemID=p.PackID;

SQL Server select parts, fill with 0 no result

I have the following tables
Location (Id, locationName)
Inventory (productid, qty, locationid)
With the following data, I need to query to show all locations per productid, even when not in inventory table. example of records below.
Table Location
Id Location Name
--------------------
1 Plant
2 Warehouse
3 Container
Table Inventory:
Productid Qty Locationid
-----------------------------
45 30 1
45 56 2
3 15 1
3 50 3
15 25 3
Desired result for my query:
Productid Qty LocationName
---------------------------------
45 30 Plant
45 56 Warehouse
45 0 Container
3 15 Plant
3 0 Warehouse
3 50 Container
15 0 Plant
15 0 Warehouse
15 25 Container
So far I have tried many different ways but no luck, so any help will be appreciated.
You can use the following query:
SELECT p.ProductId,
COALESCE(qty,0) AS qty,
[Location Name]
FROM LOCATION l
CROSS JOIN (SELECT DISTINCT ProductId FROM Inventory) AS p
LEFT JOIN Inventory i ON l.Id = i.locationid AND p.Productid = i.Productid
ORDER BY Productid, [Location Name]
The query uses CROSS JOIN to get all possible combinations between locations and products.
Demo here
Select y., isNull(z.Quantity,0) as Quantity
From
(
Select Location., x.ProductId
From Location,(Select Distinct ProductId From Inventory) as x
) as y
Left Outer Join Inventory z ON y.Id = z.LocationId
and y.ProductId = z.ProductId

SQL split one column into two columns based on values and use columns

Table: ProductionOrder
Id Ordernumber Lotsize
1 Order1 50
2 Order 2 75
3 WO-order1 1
4 WO-order2 1
Table: history
Id ProductionOrderID Completed
1 3 1
2 3 1
3 4 1
4 4 1
Table: ProductionOrderDetail
ID ProductionOrderID ProductionOrderDetailDefID Content
1 1 16 50
2 1 17 7-1-2018
3 2 16 75
4 2 17 7-6-2018
Start of my code:
Select p.ID, p.OrderNumber,
Case productionOrderDetailDefID
Where(Select pd1.productionOrderDetailDefID where ProductionOrderDetialDefID = 16) then min(pd1.content)
from ProductionOrder p
Left join History h1 on p.id = h1.productionOrderID
Left Join ProductionOrderDetail pd1 on p.ID = ProductionOrderID
The result in trying to get is
Id Ordernumber Lotsize Productionorder Completed
1 Order1 50 WO-order1 2
2 Order 2 75 WO-order2 2
Any help would be appreciated.
Try this
SELECT ordernumber,lotsize,Ordernumber,count(Ordernumberid)
FROM productionorder inner join history on productionorder.id = history.Ordernumberid
GROUP BY Ordernumber;
A bit of weird joins going on here. You should add this to a SQL fiddle so that we can see our work easier.
A link to SQL fiddle: http://sqlfiddle.com/
Here is my first attempt
SELECT
po.id
, po.ordernumber
, po.lotsize
, po2.productionorder
, SUM(h.completed)
FROM productionorder as po
INNER JOIN history as h
ON h.id = po.id
INNER JOIN prodcuctionorder as po2
ON po2.ordernumberid = h.ordernumberid
WHERE po.id NOT EXISTS IN ( SELECT ordernumberid FROM history )
GROUP BY
po.id
, po.ordernumber
, po.lotzise
, po2.productionorder
How far does that get you?

How to select rows from a group using a condition

I have a table which contains data in this format.
ProductID ShipId
11 1
11 2
11 3
22 1
22 2
33 1
33 2
Now I want only the distinct product ids where ship id 3 is not associated.
Output should be
22,33 only.
I have used this query but it throws error.
Select distinct productid from X_product_ship group by productid having shipid <> 3
Please help.
Use a subquery in the where clause to exclude the products that has a shipid of three.
select distinct P1.ProductID
from dbo.X_product_ship as P1
where P1.ProductID not in (
select P2.ProductID
from dbo.X_product_ship as P2
where P2.ShipId = 3
)
SQL Fiddle
Or you could get creative in the having clause using a case statement.
select P.ProductID
from dbo.X_product_ship as P
group by P.ProductID
having max(case when P.ShipId = 3 then 1 else 0 end) = 0
SQL Fiddle