2016-12-01 64 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