2013-07-15 38 views
1

我需要創建一個SQL視圖,將其作爲XML數據集傳遞給Crystal Reports。SQL根據數量複製了一行

我需要根據其數量重複記錄(產品編號):

例如這樣的:

| Product ID | Product Name | Quantity 
----------------------------------------- 
    0001  Product 1  5 
    0002  Product 2  3 

變爲這樣:

| Product ID | Product Name | Quantity 
----------------------------------------- 
    0001  Product 1  5 
    0001  Product 1  5 
    0001  Product 1  5 
    0001  Product 1  5 
    0001  Product 1  5 
    0002  Product 2  3 
    0002  Product 2  3 
    0002  Product 2  3 

我怎麼能重複使用基於SQL數量的記錄?

+2

你有一個Numbers表格方便(從0或1 * N *值的表,其中* N *是大數字)?如果你這樣做了,你可以在Numbers.Value <= Product.Quantity上加入它來複制行。 –

+0

我還沒有創建一個數字表 – samb90

+0

那麼我的建議是創建一個,填充數字,然後做一個簡單的連接來複制你的記錄。請參閱此處瞭解如何創建一個:http://sqlblog.com/blogs/adam_machanic/archive/2006/07/12/you-require-a-numbers-table.aspx。順便說一句,你使用哪個SQL數據庫? –

回答

3

的以下是基於遞歸公用表表達式的解決方案。

WITH CTE(ProductID, RowIndex) AS 
    (
     SELECT 
      ProductID 
      ,Quantity AS RowIndex 
     FROM [TableName] 
     WHERE Quantity > 0 
     UNION ALL 
     SELECT 
      ProductID 
      ,RowIndex - 1 
     FROM CTE 
     WHERE RowIndex - 1 > 0 
    ) 

SELECT Tbl1.* 
FROM [TableName] AS Tbl1 
INNER JOIN CTE AS Tbl2 
    ON Tbl1.ProductID = Tbl2.ProductID 
ORDER BY Tbl1.ProductID 

要使用上面的代碼,只需將TableName替換爲您的表的名稱。執行代碼後

測試表

| ProductID | ProductName | Quantity | 
-------------------------------------- 
    0001  Product 1  5 
    0002  Product 2  3 
    0003  Product 3  2 
    0004  Product 4  0 

結果

| ProductID | ProductName | Quantity | 
-------------------------------------- 
    0001  Product 1  5 
    0001  Product 1  5 
    0001  Product 1  5 
    0001  Product 1  5 
    0001  Product 1  5 
    0002  Product 2  3 
    0002  Product 2  3 
    0002  Product 2  3 
    0003  Product 3  2 
    0003  Product 3  2 
+0

感謝您的解決方案。代碼正在運行,但表中的第一個產品包含的記錄編號等於前兩個產品(Product1.Quantity + Product2.Quantity)的總數。然而,產品2包含正確數量的記錄。任何想法,爲什麼這是發生? – samb90

+0

你執行完全相同的代碼嗎? –

+0

我已經修好了:) – samb90

-1

SELECT項目。* FROM (選擇電平升 FROM DUAL CONNECT BY LEVEL < = largest_number)數據, 項 WHERE data.l < = item.quantity ORDER BY item.id

+0

這是Oracle的解決方案,而不是MSSQL。 –