I have a table name 'Product'
ProductID ProductName
1 A
2 B
3 C
4 D
Another table named 'ViewedProduct'
ProductID Views UserID
2 2 55
2 1 40
1 10 40
1 50 127.0.1
3 51 127.0.1
for UserID 55 the expected result should be
ProductID ProductName
2 B
1 A
3 C
4 D
UserID 55 views should be at top and all other viewdproduct should come after it order by sum of their views. The product id 1 viewed by two different UserIDs thei total views is 60 that why it should come in second place. and product id 3 have 51 views it should come in third place.
Second Example :
ProductID Views UserID
2 2 55
3 3 55
2 1 40
1 10 40
1 50 127.0.1
3 51 127.0.1
4 50 127.0.1
Now for UserID 55 , it should first sort the result based on UserID 55. Then comes the rest result. Now the expected result i need should be
ProductID ProductName
3 C
2 B
1 A
4 D
Product ID 3 and 2 is not top because UserId 55 has viewed this 3 and 2 times respectively, the productid 1 is on the third place UserID 55 have not viewed this product. but their total views from viewed table is 60. And productID 4 comes last because userid 55 have not viewed this product but it total views from view table is 50. and so on..
-- Please comment if you need further explanation
I've edited the query to include the userID in the join clause as I believe this is necessary. see fiddle here: http://www.sqlfiddle.com/#!3/0ef18/1
SELECT
Product.ProductID,
Product.ProductName
FROM
Product
LEFT JOIN ViewedProduct ON Product.ProductID = ViewedProduct.ProductID AND ViewedProduct.UserID = #userID
WHERE
ViewedProduct.UserID IS NULL
OR ViewedProduct.UserID = #userID
ORDER BY
CASE WHEN ViewedProduct.Views IS NULL THEN 0 ELSE ViewedProduct.Views END DESC,
Product.ProductID
To order by the following:
UserViews,
AllViews,
ProductID
Use the following:
SELECT
Product.ProductID,
Product.ProductName
FROM
Product
LEFT JOIN ViewedProduct ON Product.ProductID = ViewedProduct.ProductID AND ViewedProduct.UserID = #userID
LEFT JOIN
(SELECT
ProductID,
SUM(Views) AllViews
FROM
ViewedProduct
GROUP BY
ProductID) TotalViewedProduct ON Product.ProductID = TotalViewedProduct.ProductID
ORDER BY
CASE WHEN ViewedProduct.Views IS NULL THEN 0 ELSE ViewedProduct.Views END DESC,
TotalViewedProduct.AllViews DESC,
Product.ProductID
It's not clear what you are asking here but if you want to return results from one of these tables and sort it by a column in another table just create a join between the main table and the table that holds the column you want to sort on. This will allow you to sort on columns in the joined table.
SELECT Product.ProductID, Product.ProductName
FROM Product
LEFT JOIN ViewedProduct ON Product.ProductID = ViewedProduct.ProductID
ORDER BY ViewedProduct.UserID
This however will not return the results you expect as UserID 55 has not viewed ProductID 1 or 3 and ordering will simply order ascending or descending.
If you want products viewed by UserID 55, you'll need a where clause:
SELECT Product.ProductID, Product.ProductName
FROM Product
LEFT JOIN ViewedProduct ON Product.ProductID = ViewedProduct.ProductID
WHERE ViewedProduct.UserID = 55
This will just return one row, unless there is more data than in your sample.
If you want to order by number of views try something like:
SELECT Product.ProductID, Product.ProductName
FROM Product
LEFT JOIN ViewedProduct ON Product.ProductID = ViewedProduct.ProductID
WHERE ViewedProduct.UserID = 55
ORDER BY ViewedProduct.Views
Related
I have below tables
Order Table
OrderNo CategoryID SubCategoryID CountryID
100 7 1 3
200 8 2 5
300 7 2 4
400 2 6 2
Tracking Table
OrderNo CountryID TrackingTypeID
100 2 1
200 1 2
100 3 3
400 5 5
200 2 2
Reviewed Table
OrderNo
300
100
200
Expected Result
OrderNo SubCategoryID CategoryID CountryID CountryID
100 1 7 3 3
200 2 8 5 5
300 2 7 4 4
Each subCategory belongs to one Category.
Now I want to write a query for below requirements.
Returns only orders of CategoryID (7,8)
1.1 In case the order has SubCategoryID (1,4)
return only orders which has a record in Tracking table with
same CountryID as in Order table.
And that order should not have a TrackingTypeID of (5,6) in Tracking
table.
1.2 In case the order has SubCategoryID (2,6) then that order must
have a record in Reviewed table and that order should not have a
TrackingTypeID (5,6) in Tracking table
Exclude all orders which have SubCategoryID that not belong to CategoryID (7,8)
I wrote below script but the issue is that it's always run the second condition only.And no order which satisfies the first condition is being returned.
But if I run the script with the first condition only I get these orders. I don't know what I'm doing wrong here.
SELECT DISTINCT o.orderNo , o.subCategoryId , o.categoryId ,
o.countryId , Tracking.countryId
FROM [Order] o
JOIN Tracking ON o.orderNo = Tracking.orderNo
WHERE
(o.subCategoryId IN (1,4 ) AND o.countryId = Tracking.countryId AND
EXISTS (SELECT 1
FROM tracking t
WHERE t.orderNo = o.orderNo AND t.countryId = o.countryId)
AND NOT EXISTS ( SELECT 1
FROM tracking t
WHERE t.orderNo = o.orderNo
AND TrackingTypeID IN (5,6))
)
OR
(o.subCategoryId in (
SELECT id FROM subCatgory WHERE categoryId in (7,8)
AND ID NOT IN (1 , 4)
)
AND EXISTS (SELECT 1
FROM Reviewed r
WHERE r.orderNo = r.orderNo
)
AND NOT EXISTS ( SELECT 1
FROM tracking t
WHERE t.orderNo = o.orderNo
AND TrackingTypeID IN (5,6))
)
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
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?
Here I Have Two tables:
Orders
OrderId OrderName
1 Apple
2 Mango
Cust
Id Name OrderId Price
1 John 1 50
2 John 1 100
3 Mic 1 10
4 Mic 2 10
Sql Join Query:
SELECT Orders.CustName,Items.IteamName,Orders.Price
FROM Orders JOIN Items ON Items.Id = Orders.Id
Group By
SELECT Orders.CustName, SUM(Price) FROM Orders GROUP BY Orders.CustName
How can I Write Group by in Join?
You can do like this:
Select Orders.CustName, Items.IteamName, SUM(Orders.Price)
FROM
Orders JOIN Items ON Items.Id=Orders.Id
GROUP BY
Orders.CustName, Items.IteamName
The fields that you doesn't aggregate you put at the GROUP BYclause.
i have 3 tables Product Category and ProductCategory.
Product table:
ProductID ProductName
1 P1
2 P2
3 P3
Category table:
CategoryID CategoryName
1 C1
2 C2
3 C3
ProductCategory:
ProductID CategoryID
1 1
1 2
1 3
2 3
3 1
3 2
I need a query which returns products which fall under more than 1 categories. Based on the table data above the result would be:
ProductID ProductName
1 P1
3 P3
So i wrote a query to fetch all the ProductID's which have more than one CategoryID's as below:
select ProductID,count(CategoryID)
from ProductCategory
group by Productid
having count(CategoryID)>1)
But when i try to display product details using the below query i get an error:
select *
from Product
where ProductID in (
select ProductID,count(CategoryID)
from ProductCategory
group by Productid
having count(CategoryID)>1))
Is my query wrong? How do i get the required product details which fall in more than one categories?
Remove the COUNT() in the subquery. The result of the subquery when used on IN clause must have only one returned column.
SELECT *
FROM Product
WHERE ProductID IN
(
SELECT ProductID
FROM ProductCategory
GROUP BY Productid
HAVING count(CategoryID) > 1
)
SQLFiddle Demo
or by using JOIN
SELECT a.*
FROM Product a
INNER JOIN
(
SELECT ProductID
FROM ProductCategory
GROUP BY Productid
HAVING count(CategoryID) > 1
) b ON a.ProductID = b.ProductID
SQLFiddle Demo
You can try use CROSS APPLY Operator in SQL Server
SELECT DISTINCT C.ProductID,C.ProductName,A.CategoryID,A.Total
FROM Product C
CROSS APPLY (
Select CA.CategoryID,Total=COUNT(*)
From ProductCategory CA
Where C.ProductID=CA.ProductID
Group By CA.CategoryID Having COUNT(*)>1
) AS A
ORDER BY A.Total DESC
Take a look: http://explainextended.com/2009/07/16/inner-join-vs-cross-apply/