如何将两个不同表中的两个select语句显示为一个包含列的表

时间:2016-03-08 08:33:14

标签: sql-server

我有一个表t1,我希望按年,月找出几列的总和。

SELECT 
         SUM(SA) as SA,
        SUM(TM) as TM,
        SUM(ST) as ST       
    FROM t1
GROUP BY YEAR(createdDate), MONTH(createdDate)
ORDER BY YEAR(createdDate), MONTH(createdDate)

第二个表t2是

SELECT 
         SUM(BA) as BA,
        SUM(TR) as TR   
    FROM t2
GROUP BY YEAR(createdDate), MONTH(createdDate)
ORDER BY YEAR(createdDate), MONTH(createdDate)

各个表的输出是

表1

76.45   416.51  2484.89
80.28   296.18  1909.83
78.57   342.27  4798.71

表2

1924.9  0
1689.85 0
4608.69 0

但我想将其表示为单个表格

76.45   416.51  2484.89    1924.9   0
80.28   296.18  1909.83    1689.85  0
78.57   342.27  4798.71     4608.69 0

我没有共同的列加入。所以我必须没有加入

2 个答案:

答案 0 :(得分:1)

我不相信你的例子是完整的,你可能不需要FULL OUTER JOIN但是在知道更多就足够了之前。重点是您将年份和月份作为共同的潜在列

SELECT
      coalesce(a.yr,b.yr) yr
    , coalesce(a.mn, b.mn) mn
    , a.SA, a.TM, a.ST, b.BA, b.TR
FROM (
      SELECT
            YEAR(createdDate) yr
          , MONTH(createdDate) mn
          , SUM(SA) AS SA
          , SUM(TM) AS TM
          , SUM(ST) AS ST
      FROM t1
      GROUP BY
            YEAR(createdDate)
          , MONTH(createdDate)
      ) a
      FULL OUTER JOIN (
            SELECT
                  YEAR(createdDate) yr
                , MONTH(createdDate) mn
                , SUM(BA) AS BA
                , SUM(TR) AS TR
            FROM t2
            GROUP BY
                  YEAR(createdDate)
                , MONTH(createdDate)
      ) b ON a.yr = b.yr
                  AND a.mn = b.mn

另一种可能性是您要过滤特定日期范围(例如2014年,2015年和2016年),并且您知道这两年和几个月都有两个表中的数据,因此您使用INNER JOIN:< / p>

SELECT
      a.yr, a.mn
    , a.SA, a.TM, a.ST, b.BA, b.TR
FROM (
      SELECT
            YEAR(createdDate) yr
          , MONTH(createdDate) mn
          , SUM(SA) AS SA
          , SUM(TM) AS TM
          , SUM(ST) AS ST
      FROM t1
      where somedatecolumn >= '20140101' and somedatecolumn < '20170101'
      GROUP BY
            YEAR(createdDate)
          , MONTH(createdDate)
      ) a
      INNER JOIN (
            SELECT
                  YEAR(createdDate) yr
                , MONTH(createdDate) mn
                , SUM(BA) AS BA
                , SUM(TR) AS TR
            FROM t2
            where somedatecolumn >= '20140101' and somedatecolumn < '20170101'
            GROUP BY
                  YEAR(createdDate)
                , MONTH(createdDate)
      ) b ON a.yr = b.yr
                  AND a.mn = b.mn

答案 1 :(得分:-2)

SELECT  YEAR(createdDate) cYear, MONTH(createdDate) cDate,
     SUM(SA) as SA,
    SUM(TM) as TM,
    SUM(ST) as ST,
    T.BA,T.TR       
FROM t1 LEFT JOIN  (SELECT YEAR(createdDate) cYear, MONTH(createdDate) cDate,
     SUM(BA) as BA,
    SUM(TR) as TR   
FROM t2 GROUP BY YEAR(createdDate), MONTH(createdDate) )T ON .cYear=YEAR(t1.createdDate) AND T.cDate=MONTH(t1.createdDate) GROUP BY YEAR(t1.createdDate), MONTH(t1.createdDate),T.BA,T.TR ORDER BY YEAR(t1.createdDate), MONTH(t1.createdDate)