将查询两个表的总和与日期相结合

时间:2016-09-12 16:28:23

标签: mysql sql

我有两个表,如下面的

challenge_table

challengecount  initcount   curdate
-----------------------------------
1                2          11-02-2012
2                1          12-02-2012
1                2          13-02-2012
1                0          14-02-2012

我需要这样的结果

SELECT COUNT(*) challengecount, chdate caldate FROM challenge_table
UNION ALL 
SELECT COUNT(*) Initiatecount, indate caldate FROM init_table

我尝试过像这样的查询

from __future__ import print_function
import json
import boto3
import datetime
import time

ec2 = boto3.client('ec2')

def lambda_handler(event, context):
    try:
        print("Creating snapshots on " + str(datetime.datetime.today()) + ".")
        schedulers = ec2.describe_instances(MaxResults=50, Filters=[{'Name':'tag:GL-sub-purpose', 'Values':['Schedule']}])
        print("Performing backup on " + str(len(schedulers)) + " schedules.")
        successful = []
        failed     = []
        schedule_instances = schedulers['Instances']
        for s in schedulers:
            try:
                instanceId=s['InstanceId']
                print (instanceId)
                snapshotDescription = instanceId + "-" + str(datetime.date.today().strftime('%Y-%m-%d')) + "-46130e7ac954-automated"
                ec2.create_snapshot(
                VolumeId=s['VolumeId'], 
                Description=snapshotDescription
                )
                successful.append(instanceId)
            except Exception as e:
                print(e)
                failed.append(instanceId + " :\t" + str(e))
        print("Performed backup on " + str(len(successful)) + " schedulers. Failed backup on " + str(len(failed)) + " schedulers. ")
        sendEmail(successful, failed)
        return "Success"
    except Exception as e:
        print(e)
        return "Failed"

但它对我不起作用。

1 个答案:

答案 0 :(得分:0)

由于MySQL不支持FULL OUTER JOIN,因此需要将2个表与UNION组合使用。

然后按日期分组并计算2个表的值

select caldate, count(distinct Challenger), count(distinct Initiateid)
from
(
    SELECT Challenger, null as Initiateid, chdate as caldate FROM challenge_table
    UNION ALL 
    SELECT null, Initiateid, indate FROM init_table
) tmp
group by caldate