Pergunta

I've been playing with this for days, and can't seem to come up with something. I have this query:

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

Which gives me these results:

 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....

What I need to do is use a JOIN or something, so that I get a NULL value for each month (1-12), for each name:

 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....

I have a "Numbers" table, and have tried doing:

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)

But that only gives me 6 additional NULL rows, where what I want is actually 6 NULL rows for each group of names. I've tried using Group By, but not sure how to use it in a JOIN statement like that, and not even sure if that's the correct route to take.

Any advice or direction is much appreciated!

Foi útil?

Solução

Here's one way to do it:

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)

Outras dicas

You could do:

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top