将颜色值附加到查询结果

时间:2013-08-16 16:18:30

标签: sql sql-server tsql

我有一个问题:

declare @colors table (color varchar(50));
declare @T table(RowNo int, LocationID bigint, TotalSales money, DBAName varchar(50), Color varchar(50));

insert into @colors
select distinct Color
from dbx.dbo.SampleData;

select top 5 *
from @colors
order by newid()

insert into @T
select (row_number() over (order by LocationID)) as RowNo,
        LocationID, sum(TransAmount) as TotalSales, DBAName, Color
from dbx.dbo.SampleData
group by LocationID, DBAName, Color

select * from (
  select LocationID, TotalSales, DBAName
  from @T
) x
group by LocationID, TotalSales, DBAName

具有以下结果:

Results

我想知道如何RIGHT JOIN(或其他更好的解决方案)@colors@T,以便每行都有一个唯一的颜色值,如下所示:

What I want

我感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

您需要在两个表中添加一些公共列才能加入它们。例如,您可以在Colors表中添加一个名为LocationId的列,并为每个locationId指定唯一的颜色。然后查询将是:

Select T.LocationID, T.TotalSales, T.DBAName,C.Color
From @T t join @Colors C on T.LocationId=C.LocationId