将从2个表到1个结果集的逐月结果集合并

时间:2017-10-11 09:19:10

标签: sql sql-server

我使用以下sql

从2个表获得Monthwise结果作为2个不同的结果集
    SELECT FORMAT(CompletedDate,'MMMM yyyy')  as TestDate,COUNT(_ID) as MATCOUNT
      FROM _tableXX
      where ..........
     group by  FORMAT(CompletedDate,'MMMM yyyy')

     SELECT FORMAT(CompletedDate,'MMMM yyyy')  as TestDate,COUNT(_ID) as MATCOUNT
      FROM _tableYY
      where ..........
     group by  FORMAT(CompletedDate,'MMMM yyyy')

我们可以将这些结合到具有以下列的单个结果集

    TestDate  MATCOUNT   MATCOUNT

其中一个表中有空记录几个月

 First query returns

            June 2017   798 
            July 2017   2   
            May 2017    1189    

     Second one returns


            June 2017   285 
            May 2017    111 

     Trying to build the result set as


            June 2017   798  285
            July 2017   2    0
            May 2017    1189 111    

3 个答案:

答案 0 :(得分:1)

with c1 as ( 
    SELECT FORMAT(CompletedDate,'MMMM yyyy')  as TestDate,COUNT(_ID) as MATCOUNT
  FROM _tableXX
  where ..........
 group by  FORMAT(CompletedDate,'MMMM yyyy')
),
c2 as (
       SELECT FORMAT(CompletedDate,'MMMM yyyy')  as TestDate,COUNT(_ID) as MATCOUNT
  FROM _tableYY
  where ..........
 group by  FORMAT(CompletedDate,'MMMM yyyy')
)

select coalesce(c1.testdate, c2.testdate) as TestDate, c1.MATCOUNT, c2.MATCOUNT
FROM c1 FULL OUTER JOIN c2 on c1.testDate=c2.testDate

如果任一表中缺少一行,则相应的MATCOUNT将为null,您可以用

替换select语句
select coalesce(c1.testdate, c2.testdate) as TestDate, 
       coalesce(c1.MATCOUNT,0) as MATCOUNT,
       coalesce(c2.MATCOUNT,0) as MATCOUNT

取而代之的是

答案 1 :(得分:1)

您可以通过表之间的完全外部联接以及使用行显示 if let del = delegate, let stringData = stringTF.text, let amountData = amountTF.text { del.userDidEnterData(stringData: stringData, amountData: amountData) dismiss(animated: true, completion: nil) } 的合并来实现此目的:运行以下示例:

NULL

产地:

CREATE TABLE #temp1 ( TestDate NVARCHAR(20), MATCOUNT INT )
CREATE TABLE #temp2 ( TestDate NVARCHAR(20), MATCOUNT INT ) 

INSERT INTO #temp1 ( TestDate, MATCOUNT )
VALUES ( N'Jan 2017', 10  ),
       ( N'Feb 2017', 20  ),
       ( N'Mar 2017', 30  )

INSERT INTO #temp2 ( TestDate, MATCOUNT )
VALUES ( N'Jan 2017', 5  ), 
       ( N'Mar 2017', 15  ),
       ( N'Apr 2017', 25  )

SELECT COALESCE(t.TestDate, t2.TestDate) AS TestDate,
       COALESCE(t.MATCOUNT, 0) AS MatCount1,
       COALESCE(t2.MATCOUNT, 0) AS MatCount2
FROM #temp1 AS t
    FULL OUTER JOIN #temp2 AS t2
        ON t2.TestDate = t.TestDate;

DROP TABLE #temp1
DROP TABLE #temp2

答案 2 :(得分:0)

试试这个:

----------------
| <- =         |
----------------

<- back
=  navigation toggle button