2015-06-24 97 views
1

我試圖展示TOP 5銷售量最高的品牌。我目前只有4個品牌,因此產出表只顯示4排品牌及其細節。我希望輸出表顯示在這種情況下爲空的第五行。如何修改我的代碼以實現我想要的功能?SQL Server:顯示空行選擇TOP 5

這是我的SQL語句:

SELECT TOP 5 
    ROW_NUMBER() OVER (ORDER BY ISNULL(SUM(Product.NoSold), 0) DESC) AS No, 
    Brand.BrandName, 
    ISNULL(SUM(Product.NoSold), 0) AS NoSold 
FROM 
    Brand 
LEFT OUTER JOIN 
    Product ON Brand.BrandId = Product.BrandId 
GROUP BY  
    Brand.BrandName 
ORDER BY  
    NoSold desc 
+1

'TOP N'無效MySQL中,也不是'OVER()'。你真的使用MS SQL Server嗎?如果你嘗試在MySQL中這樣做,它將是一個語法錯誤。 –

+0

@MichaelBerkowski感謝您糾正我。是的我使用MS SQL。我改變了這一點。 – ExPlOiD

+2

什麼版本的SQL Server?你是什​​麼意思的空行?所有列爲空?你爲什麼需要這個?看起來像是應該在表示層中完成的事情。 –

回答

2

您可以使用一個Tally Tabel並對您的真實查詢執行LEFT連接。

SELECT 
    no.Number as no, 
    v.BrandName, 
    COALESCE(v.NoSold,0) NoSold 
FROM 

    master..spt_values no 
    LEFT JOIN 
    (
     SELECT TOP 5 ROW_NUMBER() over (ORDER BY ISNULL(SUM(Product.NoSold), 0) DESC) AS No, 
        Brand.BrandName, 
       ISNULL(SUM(Product.NoSold), 0) AS NoSold 
     FROM   Brand LEFT OUTER JOIN 
       Product ON Brand.BrandId = Product.BrandId 
     GROUP BY  Brand.BrandName 
     ORDER BY  NoSold desc 
    ) v 
    ON no.Number = v.No 
WHERE 
    no.Type = 'P' 
    AND no.Number between 1 and 5 

Demo with simplified inner query

0

我想你可以製造一些隨機行,聯合在一起與你的真實數據,然後用外TOP限制截斷集。還可以添加僞造訂單,以確保您的實際數據取代製造的數據。

SELECT TOP 5 No, BrandName, NoSold 
FROM 
(
    -- Your real query 
    SELECT 
     ROW_NUMBER() OVER (ORDER BY ISNULL(SUM(Product.NoSold), 0) DESC) AS No, 
     Brand.BrandName, 
     ISNULL(SUM(Product.NoSold), 0) AS NoSold, 
     1 AS OrderBy 
    FROM   
     Brand LEFT OUTER JOIN 
     Product ON Brand.BrandId = Product.BrandId 
    GROUP BY 
     Brand.BrandName 

    UNION ALL 

    -- Manufactured data. 
    SELECT NULL AS No, NULL AS BrandName, NULL AS NoSold, 0 AS OrderBy 
    FROM sys.objects 
) X 
ORDER BY OrderBy DESC, NoSold DESC; 

Fiddle here

然而,這對我來說似乎是一個表現層更好的工作 - 例如如果屏幕上確實存在5個硬編碼插槽,則可能需要對缺少的數據進行窗口裝飾,例如「即將推出的新品牌」等。

+0

'FROM sys.objects'這是故意的還是測試代碼? – Khan

+0

選擇任何保證存在的表至少5行。我們沒有從中選擇。或者使用數字模式。 – StuartLC

+0

在內存中創建表格會更有意義嗎? – Khan

0
select top 5 * from (select * from (values(null),(null),(null),(null),(null)) as Category(nil)) a 
left join Brand on 1=1 
LEFT OUTER JOIN 
      Product ON Brand.BrandId = Product.BrandId 
GROUP BY  Brand.BrandName 
ORDER BY  NoSold desc