从两个表中获取mysql join或concat查询以获得月份注册

时间:2016-03-08 16:57:03

标签: mysql join concat

我有两个表reg_dealer和claim_data。

SELECT YEAR(claim_dt) AS `Year`, 
       MONTHNAME(claim_dt) AS `Month`, 
       COUNT(distinct `uniquecode`) AS `No of Reg` 
FROM claim_data
WHERE YEAR(claim_dt) = '2016' 
GROUP BY `Year`, `Month` 
ORDER BY MONTH(claim_dt) DESC


SELECT YEAR(reg_date) AS `Year`, 
       MONTHNAME(reg_date) AS `Month`, 
       COUNT(*) AS `No of Reg`
FROM reg_dealer 
WHERE YEAR(reg_date) = '2016' 
GROUP BY `Year`, `Month` 
ORDER BY MONTH(reg_date)  DESC

我从同一格式的两个表中得到月份结果。

Year----------Month----------No_of_Reg
2016          March           150
2016          February        125
2016          Janurary         75

我希望一次性注册和申请

Year----------Month----------No_of_Reg---------No_of_claims
2016          March           150                350
2016          February        125                250
2016          Janurary         75                150

也想获得独特的索赔人

请帮助

1 个答案:

答案 0 :(得分:0)

加入查询。

SELECT t1.Year, t1.Month, `No of Reg`, `No of Claims`
FROM (SELECT YEAR(claim_dt) AS `Year`, MONTHNAME(claim_dt) AS `Month`, MONTH(claim_dt) AS MonthNum, COUNT(distinct `uniquecode`) AS `No of Claims` 
        FROM claim_data 
        WHERE YEAR(claim_dt) = '2016' GROUP BY `Year`, `Month`) AS t1
JOIN (SELECT YEAR(reg_date) AS `Year`, MONTH(claim_dt) AS MonthNum, COUNT(*) AS `No of Reg` 
        FROM reg_dealer 
        WHERE YEAR(reg_date) = '2016' 
        GROUP BY `Year`, `MonthNum`) AS t2
    ON t1.Year = t2.Year AND t1.MonthNum = t2.MonthNum
ORDER BY t1.Year, t1.MonthNum DESC