Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 添加Inset以选择缺少值的查询_Sql_Sql Server_Insert - Fatal编程技术网

Sql 添加Inset以选择缺少值的查询

Sql 添加Inset以选择缺少值的查询,sql,sql-server,insert,Sql,Sql Server,Insert,我有下面的简化表格 |---------------------|------------------|------------------| | month | customer | value | |---------------------|------------------|------------------| | 1 | A | 20

我有下面的简化表格

|---------------------|------------------|------------------|
|        month        |     customer     |      value       |
|---------------------|------------------|------------------|
|          1          |        A         |        20        |
|---------------------|------------------|------------------|
|          1          |        B         |        20        |
|---------------------|------------------|------------------|
|          1          |        C         |        20        |
|---------------------|------------------|------------------|
|          2          |        A         |        20        |
|---------------------|------------------|------------------|
|          2          |        B         |        20        |
|---------------------|------------------|------------------|
如您所见,对于第2个月,客户C没有价值

在本例中,我需要通过编程在select语句中添加month='2'customer='C'value='0'

从mytable中选择月份、客户、价值

我的实际表中有更多的行,但最终结果需要是每个月都有相同的客户列表


非常感谢您的帮助。

使用
交叉连接来生成行,使用
左连接来引入值:

select m.month, c.customer, coalesce(t.value, 0) as value
from (select distinct month from t) m cross join
     (select distinct customer from t) c left join
     t
     on t.month = m.month and t.customer = c.customer;

注意:如果您的月份或客户有其他来源,那么这些来源可能比使用
count(distinct)

更快。是否可以保证交叉联接将在左联接之前发生,或者在这种情况下,这无关紧要?此外,这还假设每个月至少有一位客户。@P.Salmon。很抱歉,我不明白你的问题。SQL查询描述正在生成的结果集。它没有指定如何生成它。优化器确定何时运行哪些操作。