我有一个包含这些列的表:
if (event.key === "Enter") {
...
}
我想为每个没有数据的公司选择日期
id, date, CompanyId, Value,..
答案 0 :(得分:1)
我们可以尝试使用日历表方法。下方标有dates
的第一个CTE生成了2017年的所有日期。然后,我们将其交叉链接到另一个CTE companies
,以查找表中出现的所有唯一公司。通过将此交叉产品添加到您的表中,我们可以找到缺少数据的每个公司的日期。
DECLARE @ENDDATE DATETIME
SET @START_DATE = '20170101'
SET @ENDDATE = '20171231'
;WITH dates AS (
SELECT @START_DATE Date
UNION ALL
SELECT Date + 1
FROM CTE_DATES
WHERE Date + 1 < @ENDDATE
),
companies AS (
SELECT DISTINCT CompanyId
FROM yourTable
)
SELECT c.CompanyId, CAST(d.Date AS Date) Date
FROM companies c
CROSS JOIN dates d
LEFT JOIN yourTable t
ON c.CompanyId = t.CompanyId AND d.Date = t.Date
WHERE
t.CompanyId IS NULL
ORDER BY
c.CompanyId, d.Date;
答案 1 :(得分:1)
在CalenderTable中使用并使用开始日期,例如-7
;WITH dates AS (
SELECT distinct Date
FROM yourtable
WHERE (Date > DATEADD(day, - 7, CONVERT(date, SYSDATETIME())))
),
companies AS (
SELECT CompanyId
FROM yourtable
WHERE (Date = DATEADD(day, - 7, CONVERT(date, SYSDATETIME())))
)
SELECT distinct c.CompanyId, CAST(d.Date AS Date) Date
FROM yourtable c
CROSS JOIN dates d
LEFT JOIN yourtable t
ON c.CompanyId = t.CompanyId AND d.Date = t.Date
join CalenderTable a on d.Date=a.Date
WHERE t.CompanyId IS NULL
ORDER BY c.CompanyId, Date
答案 2 :(得分:1)
如果您只在查找表中的日期,我会选择:
select c.companyId, d.date
from (select distinct companyId from t) c cross join
(select distinct date from t) d left join
t
on t.companyId = c.companyId and t.date = d.date
where t.companyId is null
order by c.companyId, d.date;
这个想法很简单。 cross join
在表中创建公司和日期的所有组合。 left join
/ where
过滤掉存在的那些。请注意,缺少select distinct
。这不是必需的,只会降低查询速度。
如果您要查找范围内的日期,而不管它们是否在表格中,那么日历表(是蒂姆的答案)是正确的方法。