不包含在列中的sql join包含在结果中

时间:2013-01-26 14:44:22

标签: sql sql-server-2008 join

我有两张表

id   Name    allocation
2    Ash      15
3    Alam     18
4    Rifat    20

Date   Id    Present
24     2     10
24     3     15
25     2     10
25     3     12
25     4     12

现在我想得到以下结果

     Date  Id Alloc   Present
      24   2   15     10        
      24   3   18     15
      24   4   20     NULL
      25   2   15     10
      25   3   18     12
      25   4   20     12

我已经尝试了JOIN查询,但它没有给出所需的结果 如何获得上述结果?

2 个答案:

答案 0 :(得分:4)

SELECT 
    t1.id
  , dd.date
  , t1.allocation
  , t2.present 
FROM 
    table1 AS t1                         --- all items
  CROSS JOIN
    ( SELECT DISTINCT date
      FROM table2
    ) AS dd                              --- all dates
  LEFT JOIN
    table2 AS t2                         --- present allocations
      ON  t2.id = t1.id
      AND t2.date = dd.date ;

在SQL-Fiddle测试: test (谢谢@JW。)

答案 1 :(得分:0)

还有另一种有趣的方式:

SELECT 
    t2.date,
    t1.id,
    t1.allocation,
    MAX(CASE WHEN t1.id = t2.id THEN t2.Present ELSE NULL END)
FROM 
    table1 t1, table2 t2
GROUP BY 
    t1.id, t2.date, t1.allocation
ORDER BY 
    t2.date, t1.id

被盗:SQL query inner join with 0 values

http://www.sqlfiddle.com/#!3/d2ded/44