Sql 生成不存在的行

Sql 生成不存在的行,sql,sql-server,Sql,Sql Server,对于如何在指定条件下不存在行时生成行,我有点困惑。很抱歉设置了格式,因为我不知道如何在SO文章中编写表格,但假设我有如下数据: TimePeriodID CityspanSiteKey Mean_Name Mean 2 123 Social Environment 4 2 123 Youth with Adults 3.666666746 2 123 Youth with Peers 3.5 4 123 Social

对于如何在指定条件下不存在行时生成行,我有点困惑。很抱歉设置了格式,因为我不知道如何在SO文章中编写表格,但假设我有如下数据:

    TimePeriodID    CityspanSiteKey Mean_Name   Mean
    2   123 Social Environment  4
    2   123 Youth with Adults   3.666666746
    2   123 Youth with Peers    3.5
    4   123 Social Environment  2.75
    4   123 Youth with Adults   2.555555582
    4   123 Youth with Peers    3.5
我希望在每个时间段ID中包含几个其他平均值,但只有一个
平均值
值为NULL,如下所示:

TimePeriodID    CityspanSiteKey Mean_Name   Mean
2   123 Social Environment  4
2   123 Youth with Adults   3.666666746
2   123 Youth with Peers    3.5
2   123 Staff Build Relationships and Support Individual Youth  NULL
2   123 Staff Positively Guide Behavior NULL
4   123 Social Environment  2.75
4   123 Youth with Adults   2.555555582
4   123 Youth with Peers    3.5
4   123 Staff Build Relationships and Support Individual Youth  NULL
4   123 Staff Positively Guide Behavior NULL
5   123 Social Environment  2.75
5   123 Youth with Adults   2.555555582
5   123 Youth with Peers    3.5
5   123 Staff Build Relationships and Support Individual Youth  NULL
5   123 Staff Positively Guide Behavior NULL
6   123 Social Environment  NULL
6   123 Youth with Adults   NULL
6   123 Youth with Peers    NULL
6   123 Staff Build Relationships and Support Individual Youth  NULL
6   123 Staff Positively Guide Behavior NULL

做这件事最好的方法是什么?因为这些记录不存在,所以我认为装箱没有多大用处

您似乎想要一个
交叉连接
,然后
左连接
。并非所有值都在原始数据中,因此您不妨构造它们:

select ti.timeperiod, c.CityspanSiteKey, m.mean_name, t.mean
from (values (2), (4), (5), (6)
     ) ti(timeperiod) cross join
     (values (123)
     ) c(CityspanSiteKey) cross join
     (values ('Social Environment'), ('Youth with Adults'), ('Youth with Peers'), ('Staff Build Relationships and Support Individual Youth'), ('Staff Positively Guide Behavior')
     ) m(mean_name) left join
     t
     on t.timeperiod = ti.timeperiod and
        t.CityspanSiteKey = c.CityspanSiteKey and
        t.mean_name = m.mean_name;

您可以使用子查询或现有表来代替
values()
子句。

什么是“每个时间段ID”?简单编码,新的平均值名称是否存储在数据库中的任何位置?