我想检查产品是否是十大产品之一(从Sales.SalesOrderDetails销售的眼睛一侧)制作一列并将其设置为YES或NO
我有MAX的十大产品销售如下:
SELECT TOP 10 p.Name , COUNT(*) 'Num of sell' FROM Sales.SalesOrderDetail SOD
inner join Production.Product p on SOD.ProductID = p.ProductID
GROUP BY p.Name
ORDER BY COUNT(*) DESC
现在我想要另一个表,它是所有产品,我想以某种方式放置一个带有if / else语句的列,并在那里放置yes或no。像:
SELECT p.Name, @someVariable FROM Production.Product p
IF p.Name IN
(SELECT TOP 10 p.Name , COUNT(*) 'Num of sell' FROM Sales.SalesOrderDetail SOD
inner join Production.Product p on SOD.ProductID = p.ProductID
GROUP BY p.Name
ORDER BY COUNT(*) DESC)
@someVariable = 'YES'
ELSE @someVariable = 'NO'
任何想法?
答案 0 :(得分:3)
你可以这样做:
SELECT p.Name,
CASE WHEN X.ProductID IS NULL THEN 'NO' ELSE 'YES' END AS InTopTen
FROM Production.Product p
LEFT JOIN
(
SELECT TOP 10 ProductID FROM Sales.SalesOrderDetail
GROUP BY ProductID
ORDER BY COUNT(*) DESC
) X
ON X.ProductID = p.ProductID