在下面的查询中我在产品表中有2个表产品和产品状态我有productid,productname和productstatus表我有locationid,productid,currentstock,unitprice,statu。我想写一个相关的查询来获取productname ,currentstock,locationid.i试过,但它显示所有产品名称没有currentstock.I无法根据日期和locationid.Pls帮助我这样做。
相关子查询
SELECT p.ProductID,
p.ProductName,
(SELECT CurrentStock
FROM ProductStatus PS
WHERE PS.ProductID =p.ProductID
AND PS.LocationID = 1
AND PS.Statu = '2014-10-14')
FROM Product P
表结构和数据
CREATE TABLE #Product
(productid INT,productname VARCHAR(100))
INSERT INTO #Product
VALUES (1,'biscuit'),
(2,'soap'),
(3,'flower')
CREATE TABLE #Productstatus
(
locationid INT,
productid INT,
currentstock INT,
unitprice INT,
statu DATE
)
INSERT INTO #Productstatus
VALUES (1,1,200,10,'2014-10-14'),
(1,2,300,10,'2014-11-16'),
(2,3,200,10,'2014-12-12')
答案 0 :(得分:0)
使用相关子查询。
SELECT p.ProductID,
p.ProductName,
(SELECT CurrentStock
FROM #Productstatus PS
WHERE PS.ProductID =p.ProductID
AND PS.LocationID = 1
AND PS.Statu = '2014-10-14'
and PS.productid=p.productid) CurrentStock
FROM #Product P
答案 1 :(得分:0)
尝试并让我知道...也指定输出你想要的内容,这样就很容易为你准备查询。
-- Data only with Stock
SELECT p.PRODUCTID, p.PRODUCTNAME, ps.LOCATIONID,ps.CURRENTSTOCK,ps.UNITPRICE
FROM
PRODUCT p INNER JOIN PRODUCTSTATUS ps
ON p.PRODUCTID = ps.PRODUCTID
WHERE ps.STAT ='2014-10-14'
-- Data with /without Stock
SELECT p.PRODUCTID, p.PRODUCTNAME, ps.LOCATIONID,ps.CURRENTSTOCK,ps.UNITPRICE
FROM
PRODUCT p LEFT JOIN PRODUCTSTATUS ps
ON p.PRODUCTID = ps.PRODUCTID