sql - 编写 SQL 查询来替换值并包含所有日期

标签 sql sql-server replace isnull

嗯,我有这个 -

Table DimDate- Date 
Table Employee-  Id,Name,Points,Date

现在,员工表每天都有积分,除非他们没有来...所以日期没有所有日期条目...我的意思是,例如,在一周内,他有 2 天没有来,员工表有只有 5 行...所以我有这个暗淡日期表,其中包含 2050 年之前的所有日期,我想将其加入并为他没有积分的日期添加零。所以我写了这个查询但不起作用 -

Select E.EmployeeId,D.Date,isNull(E.Points,0) from DimDate D left join Employee E on D.Date between '01-01-2009'and '06-01-2009' where E.EmployeeId=1

上面的查询给出了多个日期,我尝试对日期进行分组,但不起作用。

最佳答案

您可能不想在日期范围上连接两个表,而是在日期上连接。然后按日期范围过滤记录集。示例

Select 
  E.EmployeeId,
  D.Date,
  isNull(E.Points,0)  
from DimDate D 
left join Employee E on D.Date = E.Date 
where E.EmployeeId=1 
  AND D.Date Between '01-01-2009'and '06-01-2009'

编辑:

Select 
  E.EmployeeId,
  D.Date,
  isNull(E.Points,0)  
from DimDate D 
left join Employee E on D.Date = E.Date And E.EmployeeId=1
where D.Date Between '01-01-2009'and '06-01-2009'

或者

Select 
  E.EmployeeId,
  D.Date,
  isNull(E.Points,0)  
from DimDate D 
left join Employee E on D.Date = E.Date 
where (E.EmployeeId = 1 OR E.EmployeeId is NULL) 
  AND D.Date Between '01-01-2009'and '06-01-2009'

关于sql - 编写 SQL 查询来替换值并包含所有日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2867669/

相关文章:

php - 用 0 替换平面数组中的所有值

python - 如何递归替换嵌套字典键中的字符?

javascript - 根据用户输入替换而不是附加?

mysql - 我可以在一个 SQL 语句中从 2 个表中删除行吗?

php - MySQL 错误 - 未知列 - 需要编辑

sql-server - SQL Server : query to get multiple results in one field

sql - 从列值中查找缺少的键 ID 或数字

sql - PostgreSQL 对数组不区分大小写的 SELECT

sql - 从远程 SQL Server 加载 SQLite 数据库?

SQL 查询查找未命名列的 INSERT 存储过程