2013-05-21 36 views
1

我使用MSSQL 2008 R2不同的時間,SQL Server 2008中:TSQL,選擇相同的數據基於列的值

我有以下結構

create table #temp (
    product int, 
    [order] int, 
    ord_qnty int 
    ) 

    insert #temp 
    select 10 ,3,4 

現在,如果ord_qnty是4,我想選擇同樣的產品,責令四次,但在所有的四排thevalue ord_qnty的應該是1,即

出來放應

Product order ord_qnty 
    10  3  1 
    10  3  1 
    10  3  1 
    10  3  1 

回答

2

嘗試這一個 -

查詢:

DECLARE @temp TABLE 
(
     product INT 
    , [order] INT 
    , ord_qnty INT 
) 
INSERT @temp(product, [order], ord_qnty) 
SELECT 10, 3, 4 

SELECT 
     t.product 
    , t.[order] 
    , ord_qnty = 1 
FROM @temp t 
JOIN [master].dbo.spt_values sv ON t.ord_qnty > sv.number 
WHERE sv.[type] = 'p' 

SELECT 
     t.product 
    , t.[order] 
    , ord_qnty = 1 
FROM @temp t 
JOIN (
    SELECT number = ROW_NUMBER() OVER (ORDER BY (SELECT 1)) 
    FROM sys.system_parameters p  
) sv ON t.ord_qnty >= sv.number 

輸出:

product  order  ord_qnty 
----------- ----------- ----------- 
10   3   1 
10   3   1 
10   3   1 
10   3   1 

查詢費用:

proff

對於任何 「數以百萬計值」:

SET NOCOUNT ON; 

DECLARE @numbers TABLE (number INT) 

DECLARE @temp TABLE 
(
     product INT 
    , [order] INT 
    , ord_qnty INT 
) 
INSERT @temp(product, [order], ord_qnty) 
SELECT 10, 3, 4 

DECLARE 
     @i BIGINT = 1 
    , @max BIGINT = (
      SELECT MAX(ord_qnty) 
      FROM @temp 
     ) 

WHILE (@i <= @max) BEGIN 

    INSERT INTO @numbers (number) 
    VALUES (@i), (@i+1), (@i+2), (@i+3), (@i+4), (@i+5), (@i+6), (@i+7), (@i+8), (@i+9) 
    SELECT @i += 10 

END 

SELECT 
     t.product 
    , t.[order] 
    , ord_qnty = 1 
FROM @temp t 
CROSS JOIN (
    SELECT * 
    FROM @numbers 
    WHERE number < @max + 1 
) t2 
+0

@Nishad,請問你是什麼不喜歡我的回答? – Devart

+0

THERZ沒什麼,我不喜歡:),有什麼,你問? – Nishad

+0

感謝您的回答。 :) – Devart

4

如果你有一個數字表,你可以使用它。如果沒有,你可以生成一個:

;with Numbers(n) as (
    select ROW_NUMBER() OVER (ORDER BY object_id) from sys.objects 
) 
select product,[order],1 as ord_qnty 
from #temp t inner join Numbers num 
    on t.ord_qnty >= num.n 

(在我的近空的臨時數據庫中,ROW_NUMBER()產生77行。如果這不會是不夠的,你可以引入交叉連接或使用其他招數來產生更多號碼,也可以創建並填充一個永久編號表)