问题
I have a company table (CompanyID, CompanyName), Date Table (Datekey int, date, isTradingHoliday 0/1), Fact table (id, datekey, companyID, StockClosePrice)
I need an exception report. Expectation is for all the companies, for all trading days, there will be a StockClosePrice. I need to find for which date and for which companies on the trading days I don't have data.
So basically, I need help to write a query to find for year 2019 for which days and for which companies I don't have data in the fact table.
回答1:
If I followed you correctly, you can cross join companies and dates, and then filter on "missing" facts on non-trading holidays with not exists
:
select c.*, d.*
from companies c
cross join dates d
where
d.isTradingHoliday = 0
and not exists (
select 1 from facts f where f.datekey = d.datekey and f.companyID = c.companyID
)
回答2:
DECLARE @Year int = 2019
SELECT *
FROM FactTable FT
LEFT JOIN CompanyTable CT ON CT.CompanyID = FT.companyID
LEFT JOIN DateTable DT ON DT.Datekey = FT.datekey
WHERE
YEAR(DT.DateField) = @Year
AND (
CT.CompanyID IS NULL
OR DT.Datekey IS NULL
)
来源:https://stackoverflow.com/questions/61807952/sql-help-exception-report