用另一个 table 中的值填充 SQL 中的列

Populate a column in SQL with values from another table

这是我的第一个 post,如果格式不正确,请见谅。

我正在为饼图和每一行创建数据集,我需要从颜色 [=32] 添加颜色 (COL_COL) 和颜色突出显示 (COL_HIG) =] 看起来像这样。

CREATE TABLE [dbo].[T_COL](
    [COL_SEQ] [int] IDENTITY(1,1) NOT NULL,
    [COL_COL] [nvarchar](20) NULL,
    [COL_HIG] [nvarchar](20) NULL,
    [COL_NAM] [nvarchar](50) NULL,
    [COL_DEL] [bit] NOT NULL,
) 

INSERT INTO [dbo].[T_COL]           ([COL_COL]
           ,[COL_HIG]
           ,[COL_NAM]
           ,[COL_DEL])
     VALUES
           ('#F7464A', '#FF5A5E','Red', 0), 
           ('#46BFBD', '#5AD3D1','Green', 0), 
           ('#FDB45C', '#FFC870','Yellow', 0), 
           ('#949FB1', '#A8B3C5','Grey', 0), 
           ('#4D5360', '#616774','Dark Grey', 0)

从审核中生成我的数据的 SQL table 是 ...

select count(*) as 'Visits', 
    datename(mm, AUD_DAT) as 'Month',
    'Unique Visits by Month' as 'Title',
    datepart(mm, AUD_DAT) as 'MonthNo',
      ROW_NUMBER() OVER (ORDER BY datename(mm, AUD_DAT)) AS 'rownum',
     null as 'colour',
     null as 'ColHightlight'
     into #temp
    from dbo.T_AUD
    where AUD_TYP_SEQ = 3 and datepart(year, AUD_DAT) = @year
    group by datename(mm, AUD_DAT),datepart(mm, AUD_DAT)
    order by datepart(mm, AUD_DAT)

以上查询returns8行,颜色table中有五种颜色。我试图达到第 1-5 行包含颜色 1-5 的地步,然后第 6 行将包含颜色 1,第 7 行包含颜色 2,依此类推。我不想对颜色的数量进行硬编码,而是使用颜色的计数 table,因为当颜色添加到 table 时计数会发生变化。

我尝试使用 row_number 函数,但它只会为每一行递增一个数字,我不确定在达到颜色计数时是否可以将其重置为 1 table.

你能帮我实现这个吗?任何帮助表示赞赏。 尼克.

如果我没理解错的话,你可以用模运算来做你想做的。我不清楚您引用的表格与您的问题有什么关系("colors" 表格应该是 t_col 吗?我不知道)。

以下查询提供了解决此问题的方法:

with yourquery as (
      <your query>
     )
select y.*, c.*
from yourquery y join
     (select c.*, row_number() over (order by id) as seqnum,
             count(*) over () as numcolors
      from colors
     ) c
     on y.rownum % c.numcolors = c.seqnum - 1;

注意:您应该只对字符串和日期常量使用单引号。不要对列别名使用单引号。

做这样的事情。 ctecolors 将用 rn(0, 1, 2, 3, 4) 标记行。 teaud 将标记 rn(0, 1, 2, 3, 4, 0, 1....)。然后在 rn.

上进行简单的连接
;with ctecolors as
(select *, -1+row_number() over(order by (select 1)) rn from [dbo].[T_COL]),

cteaud as
(   select count(*) as 'Visits', 
    datename(mm, AUD_DAT) as 'Month',
    'Unique Visits by Month' as 'Title',
    datepart(mm, AUD_DAT) as 'MonthNo',
      (-1+ROW_NUMBER() OVER (ORDER BY datename(mm, AUD_DAT))) % 5 AS rn
    from dbo.T_AUD
    where AUD_TYP_SEQ = 3 and datepart(year, AUD_DAT) = @year
    group by datename(mm, AUD_DAT),datepart(mm, AUD_DAT))

Select Visits,Month,Title,MonthNo, ctecolors.* into #temp
from ctecolors cc
join cteaud ca on cc.rn = ca.rn