2016-12-01 65 views
0

完整问题:每种产品的报告,其现有库存的百分比值,以百分比表示所属的产品线的库存。按产品线和产品线下降百分比值排序报告。显示带有两位小数的百分比。相关子查询:“其现有库存的百分比值,作为产品线现有库存的百分比”

数据库:http://richardtwatson.com/dm6e/images/general/ClassicModels.png

我尝试......

SELECT P.productCode, ((P.quantityinStock* '100,2')/(SELECT MAX(P.quantityInStock) 
FROM Products P)) AS Percent_ 
FROM Products P 
WHERE P.productCode= (SELECT ((COUNT(Q.productLine *100.0)))/(SELECT MAX(Q.productLine)) 
FROM ProductLines Q 
WHERE Q.productLine= P.productCode 
ORDER BY Q.productLine DESC) 

我奋力颇有几分与这些相关子查询!

回答

1

这是你想要的吗?

;WITH Products(productCode,quantityinStock,productLine) AS (
    SELECT 'Product1',20,'Line1' UNION ALL 
    SELECT 'Product2',60,'Line1' UNION ALL 
    SELECT 'Product3',30,'Line2' UNION ALL 
    SELECT 'Product4',30,'Line2' UNION ALL 
    SELECT 'Product5',30,'Line2' 
) 
SELECT P.*,ROUND(P.quantityinStock*1.0/SUM(P.quantityInStock)OVER(PARTITION BY p.productLine)*100,2) AS StockPercent 
FROM Products P 
ORDER BY p.productLine desc 
 
productCode quantityinStock productLine StockPercent 
----------- --------------- ----------- --------------------------------------- 
Product4 30    Line2  33.330000000000 
Product5 30    Line2  33.330000000000 
Product3 30    Line2  33.330000000000 
Product2 60    Line1  75.000000000000 
Product1 20    Line1  25.000000000000 
+0

完美!谢谢! – binmop

0

下面是如何得到的答案为例,虽然它不使用相关子查询,我会离开的排序和显示到小数点后两位给你:

Select ... 
    p.QuantityInStock * 100.0/l.LineQtyInStock As [Percent] 
    From #product As p 
    Join (
    Select Sum(QuantityInStock) As LineQtyInStock, 
     ProductLine 
     From #product 
     Group By ProductLine) As l On p.ProductLine = l.ProductLine; 

,你进了当您尝试使用MAX()时会遇到一些麻烦,如果您实际上想要SUM()的数量为productLine,则返回最高的quantityInStock

+0

谢谢你的帮助! – binmop