0

以以下查询为例:

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() 函数来显示..

4

1 回答 1

1

你的解释有些不清楚。

要在这种情况下获得所需的结果,您可以使用 aCROSS JOIN而不是 aRIGHT 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 
于 2013-06-14T12:01:14.247 回答