2014-09-29 141 views
0

我想從SQL Server表中區分兩列。我得到這個結果 - 我可以優化這個查詢嗎?在SQL Server中優化SELECT查詢

create TABLE #Temporary_tbl 
(        
    ProductColour VARCHAR(50), 
    ProductSize VARCHAR(20), 
) 

insert into #Temporary_tbl (ProductColour) 
    select distinct productcolour 
    from shoptransfer 

insert into #Temporary_tbl (ProductSize) 
    select distinct ProductSize 
    from shoptransfer 

select * from #Temporary_tbl 

我試試這個:

select distinct ProductColour, null as ProductSize 
from shoptransfer 

union all 

select distinct null as ProductColor, ProductSize 
from shoptransfer 
+3

你的查詢是好的。什麼是問題? – 2014-09-29 16:47:13

回答

0

我認爲這個問題是您的期望:我猜要顏色中的一種獨特的名單和大小的一個獨特的名單,但你希望它們出現在相同的結果表,就像這樣:

Colour  Size 
blue  10 
green  12 
orange  14 

即使有藍色&大小10等之間沒有關係這不是數據有很大的表現,因爲會發生什麼WH有5種顏色,但有100種尺寸。

您可以通過分別選擇每個DISTINCT列表和ROW_NUMBER(),然後連接行號來完成此操作。這不是SQL的真正用處,但我可以理解,有時候您想要做這種事情來報告原因。

select productSize, productColour 
from ( 
    -- get the colours and a row number 
    select productColour, row_number() over (order by productColour) as rownum 
    from (select distinct productColour from shoptransfer) as c1 
) as colours 
-- full outer join so the row numbers match and you get all the rows from both 
full outer join ( 
    -- get the sizes and a row number 
    select productSize, row_number() over (order by productSize) as rownum 
    from (select distinct productSize from shoptransfer) as s1 
) as sizes 
on colours.rownum = sizes.rownum 
0
;WITH CTE AS 
(
select ProductColour , null as ProductSize 
from shoptransfer 
GROUP BY ProductColour 

union all 

select null as ProductColor, ProductSize 
from shoptransfer 
GROUP BY ProductSize 
) 
SELECT * FROM CTE 
0

取決於你如何想在座數據的其他建議也許+ PIVOT

select * from (
    SELECT distinct  
    [ProductColor] as 'tata_column', 'ProductColor' as 'P_TAG'  
    FROM shoptransfer 
union all 
    SELECT distinct 
    [ProductSize] as 'data_colunm' , 'ProductSize' as 'P_TAG' 
    FROM shoptransfer 
    ) A 

我將消除TEMP表運行更快

請注意與大記錄集使用「WITH CLAUSE」將放慢,並可能崩潰服務器!