我希望从SQL Server表中区分出两列。我得到了这个结果 - 我可以优化这个查询吗?
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
答案 0 :(得分:0)
我认为问题是你的期望:我猜想要一个不同的颜色列表和一个不同的尺寸列表,但是你希望它们出现在同一个结果表中,如下所示:
Colour Size
blue 10
green 12
orange 14
即使蓝色和蓝色之间没有任何关系10号等等。这不是一个很好的数据表示,因为当有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
答案 1 :(得分: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
答案 2 :(得分: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"随着巨大的记录设置将缓慢下降,可能会崩溃服务器!!!