为日期不存在的每个组获取额外的行

时间:2014-05-09 16:34:15

标签: sql join

我已经玩了好几天了,似乎无法想出一些东西。我有这个问题:

select 
  v.emp_name as Name
  ,MONTH(v.YearMonth) as m 
  ,v.SalesTotal as Amount
from SalesTotals

这给了我这些结果:

 Name         m         Amount
 Smith        1         123.50
 Smith        2          40.21
 Smith        3         444.21
 Smith        4          23.21
 Jones        1         121.00
 Jones        2         499.00
 Jones        3          23.23
 Jones        4          41.82
 etc....

我需要做的是使用JOIN或其他东西,以便每个月(1-12)获得一个NULL值,每个名称​​

 Name         m         Amount
 Smith        1         123.50
 Smith        2          40.21
 Smith        3         444.21
 Smith        4          23.21
 Smith        5           NULL
 Smith        6           NULL
 Smith        ...         NULL
 Smith        12          NULL
 Jones        1         121.00
 Jones        2         499.00
 Jones        3          23.23
 Jones        4          41.82
 Jones        5           NULL
 Jones        ...         NULL
 Jones        12          NULL
 etc....

我有一个“数字”表,并尝试过:

select 
  v.emp_name as Name
  ,MONTH(v.YearMonth) as m 
  ,v.SalesTotal as Amount
from SalesTotals
   FULL JOIN Number n on n.Number = MONTH(v.YearMonth) and n in(1,2,3,4,5,6,7,8,9,10,11,12)

但是这只给了我6个额外的NULL行,其中我想要的实际上是每组名称的6个NULL行。我已经尝试过使用Group By,但不知道如何在JOIN语句中使用它,甚至不确定这是否是正确的路径。

非常感谢任何建议或指示!

2 个答案:

答案 0 :(得分:2)

以下是一种方法:

select 
  s.emp_name as Name
  ,s.Number as m 
  ,st.salestotal as Amount
from (
  select distinct emp_name, number
  from salestotals, numbers 
  where number between 1 and 12) s left join salestotals st on 
    s.emp_name = st.emp_name and s.number = month(st.yearmonth)

答案 1 :(得分:1)

你可以这样做:

SELECT  EN.emp_name Name,
        N.Number M,
        ST.SalesTotal Amount
FROM (  SELECT Number 
        FROM NumberTable
        WHERE Number BETWEEN 1 AND 12) N
CROSS JOIN (SELECT DISTINCT emp_name
            FROM SalesTotals) EN
LEFT JOIN SalesTotals ST
    ON N.Number = MONTH(ST.YearMonth)
    AND EN.emp_name = ST.emp_name