SQL help - exception report

烈酒焚心 提交于 2021-01-29 16:02:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!