我想在以下情况下获取数据

时间:2019-08-19 06:56:33

标签: sql sql-server

 Table 1                                     Table2
    Name       Month     Cast                   Month
    --------------------------                  ----------------
    Client1    Jan       200                    Jan
    Client1    Feb       150                    Feb
    Client2    Jan       110                    Mar
    Client2    Apr       120                    .
                                                .
                                                Dec





Ouput
-----------------------
Name      Month    Cast
--------------------------
Client1   Jan      200
Client1   Feb      150
Client1   Mar      0
Client1   Apr      0
...
....
Client2   Jan     110
Client2   Feb     0
Client2   Mar     0
Client2   Apr     120
Client2   May     0
.....
....

结果必须显示所有月份(如果未转换为0)的所有客户,而这些月份可能不在表1中。 我已经尝试过正确的外部连接和交叉连接...没有结果。

3 个答案:

答案 0 :(得分:2)

您可以在脚本下方尝试此操作-

 SELECT A.Name,B.month,COALESCE(C.Cast,0) Cast
 FROM (
    SELECT DISTINCT  1 CN, Name FROM Table1
 ) A
 INNER JOIN (
    SELECT 1 CN,    month FROM Table2
 ) B ON A.CN = B.CN
 LEFT JOIN Table1 C 
 ON A.Name = C.Name
 AND B.month = C.Month

答案 1 :(得分:2)

您必须先创建笛卡尔乘积(cte ClientMonth),然后再联接回原始表以获取所需的数据...

With ClientMonth as (
                  select Distinct Name,t2.[Month] 
                  from Table_1 t1
                  Cross Join  Table_2 t2
                  )
Select cm.Name, cm.[Month], isnull(amt,0)
from ClientMonth cm
Left Join Table_1 t3 on t3.Name = cm.Name and t3.Month = cm.Month

答案 2 :(得分:0)

尝试一下。

SELECT name, m1 as month ,max(cast) as cast from
(
SELECT [id]
  ,[name]
  ,b.month as m1
  ,case when a.month =b.month then [cast] else 0 end as cast
 FROM [Table_1] a,[Table_2] b
)c
group by name,m1
order by name