在SQL Server中查询每行的名称(颜色)不同

时间:2018-02-01 11:31:51

标签: sql sql-server

我需要在sql中创建一个查询,其中一个字段具有不同的颜色名称!

我需要这个,因为有些程序会读取那种颜色,是否有某种方法可以做到这一点?

例如我有这个查询

select distinct ref from table 

有了这个输出!

ref
170015              
170103              
170118              
170120              
170157              
180002              
180004    

我需要这样的东西

ref        color
170015      rgb(0,0,0)        
170103      rgb(0,0,125)        
170118      rgb(0,125,0)        
170120      rgb(125,0,0)        
170157      rgb(0,0,250)        
180002      rgb(0,250,0)       
180004      rgb(250,0,0)
...         ...  

   ref        color
170015      0        
170103      8192000        
170118      32000        
170120      125        
170157      16384000        
180002      64000       
180004      250
...         ...  

我需要多于或少于30种不同的颜色

在某种程度上这是可能的吗?

先谢谢了!

1 个答案:

答案 0 :(得分:0)

首先,在另一个表中创建颜色值列表。

with prettycolours as
(
select colourvalue, row_number() over(order by uniqueidentifier) cn
from colours
)
, CTE as
(
select a1.ref, row_number() over (order by a1.ref) rn
from (select distinct ref from MyTable) a1
)
select ref, colourvalue
from CTE
inner join prettycolours
  on rn = cn

仅当颜色多于refs

时才有效

如果没有,你需要一些其余的聪明才能

with prettycolours as
(
select colourvalue, row_number() over(order by uniqueidentifier)-1 cn
from colours
)
, CTE as
(
select a1.ref, (select max(cn) from prettycolours) % row_number() over (order by a1.ref) rn
from (select distinct ref from MyTable) a1
)
select ref, colourvalue
from CTE
inner join prettycolours
  on rn = cn