SQL, Calendar and Primary key

风流意气都作罢 提交于 2020-01-17 06:42:10

问题


I'm currently stuck on a SQL related issue, and I hope I will find help among you. Here is my issue: I have a Fact table, with column DATE, B and C being the key, and VALUE being the fact value. I also have a Referential Calendar table. What I want is, for each existing tuple B-C, and for each Date of my calendar (even if there is no fact on this date, retrieve a line.

For instance, let's assume I have:

Calendar (DD-MM-YYYY)
01-01-2015
02-01-2015
03-01-2015

and Fact

Date       | B  | C  | VALUE
=============================
02-01-2015 | aa | xx | 10
02-01-2015 | aa | yy | 15
03-01-2015 | aa | xx | 10

I want:

01-01-2015 | aa | xx | 0
01-01-2015 | aa | yy | 0
02-01-2015 | aa | xx | 10
02-01-2015 | aa | yy | 15
03-01-2015 | aa | xx | 10
03-01-2015 | aa | yy | 0

How could I do that in an efficient way?

Thanks in advance for any help you can provide.


回答1:


First create the Cartesian product calendar dates with unique values of B and C column in FACT table

Then Outer join`` the result of first step withfact` table to get the result

Try something like this

;WITH cte 
     AS (SELECT Ca.dates, C, B
         FROM   (SELECT DISTINCT C, B 
                 FROM   fact) A 
                CROSS JOIN calendar Ca) 
SELECT A.dates, 
       A.B, 
       A.C, 
       Isnull(F.value,0) as value
FROM   cte A 
       LEFT OUTER JOIN fact F 
                    ON A.dates = f.dates 
                       AND A.C = F.C 
                       AND A.B = F.B 


来源:https://stackoverflow.com/questions/34397557/sql-calendar-and-primary-key

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