SQL Query正确进行外部连接的正确方法?

时间:2013-06-14 11:42:38

标签: tsql outer-join

以下面的查询为例:

SELECT t1.itemid,
       t2.yearcreated
FROM   (SELECT '100051' AS 'itemid',
               '2012'   AS yearcreated
        UNION
        SELECT '100051' AS 'itemid',
               '2013'   AS yearcreated
        UNION
        SELECT '100052' AS 'itemid',
               '2011'   AS yearcreated
        UNION
        SELECT '100052' AS 'itemid',
               '2012'   AS yearcreated
        UNION
        SELECT '100052' AS 'itemid',
               '2013'   AS yearcreated) t1
       RIGHT OUTER JOIN (SELECT '2011' AS yearcreated
                         UNION
                         SELECT '2012'
                         UNION
                         SELECT '2013') t2
         ON t1.yearcreated = t2.yearcreated
ORDER  BY t1.itemid,
          t2.yearcreated 

它给出了这个结果:

100051  2012
100051  2013
100052  2011
100052  2012
100052  2013

为了每年获得1排,我需要改变什么呢?

100051  2011(desired new row generated by correct outer join)
100051  2012
100051  2013
100052  2011
100052  2012
100052  2013

考虑到实际查询将有更多列需要分组或min()函数显示..

1 个答案:

答案 0 :(得分:1)

您的解释有点不清楚。

要在此实例中获得所需结果,您可以使用CROSS JOIN而不是RIGHT JOIN

SELECT DISTINCT  t1.itemid,
       t2.yearcreated
FROM   (SELECT '100051' AS 'itemid',
               '2012'   AS yearcreated
        UNION
        SELECT '100051' AS 'itemid',
               '2013'   AS yearcreated
        UNION
        SELECT '100052' AS 'itemid',
               '2011'   AS yearcreated
        UNION
        SELECT '100052' AS 'itemid',
               '2012'   AS yearcreated
        UNION
        SELECT '100052' AS 'itemid',
               '2013'   AS yearcreated) t1
       CROSS JOIN (SELECT '2011' AS yearcreated
                         UNION
                         SELECT '2012'
                         UNION
                         SELECT '2013') t2
ORDER  BY t1.itemid,
          t2.yearcreated