使用分组依据分组的列中的重复日期

时间:2016-08-10 07:00:20

标签: sql group-by duplicates zoho

我试图使用group by从多个表中获取具有相同日期的行数,但结果行显示重复的日期。我更改了日期格式,仅显示日期列中的日期删除时间。

SELECT
 userprofiles."date",
 COUNT(userprofiles."date") AS NumberofRegistration,
 COUNT(CallScheduleTableFB."Date") AS NumberofCalls
FROM  userprofiles LEFT JOIN CallScheduleTableFB ON userprofiles."date"  = CallScheduleTableFB."Date"  
GROUP BY  userprofiles."date" 
UNION
SELECT
 CallScheduleTableFB."Date",
 COUNT(userprofiles."date") AS NumberofRegistration,
 COUNT(CallScheduleTableFB."Date") AS NumberofCalls
FROM  userprofiles RIGHT JOIN CallScheduleTableFB ON userprofiles."date"  = CallScheduleTableFB."Date"  
GROUP BY  CallScheduleTableFB."Date"

EDIT 以下是输出

userprofiles.date |NumberofRegistration |NumberofCalls
27/07/2016 |1 |0
28/07/2016 |0 |1
28/07/2016 |0 |1
28/07/2016 |0 |1
28/07/2016 |0 |1
30/07/2016 |0 |1
30/07/2016 |0 |1
03/08/2016 |1 |0
03/08/2016 |1 |0
03/08/2016 |0 |1
03/08/2016 |0 |1

2 个答案:

答案 0 :(得分:1)

如果我理解正确,既然您要计算两个表中的值,则需要单FULL OUTER JOIN的{​​{1}}。

像这样:

COUNTS

SELECT COALESCE(A.date, B.Date), COALESCE(A.NumberofRegistration, 0), COALESCE(B.NumberofCalls, 0) FROM ( SELECT userprofiles."date", COUNT(userprofiles."date") AS NumberofRegistration FROM userprofiles GROUP BY userprofiles."date" ) AS A FULL OUTER JOIN ( SELECT CallScheduleTableFB."Date", COUNT(CallScheduleTableFB."Date") AS NumberofCalls FROM CallScheduleTableFB GROUP BY CallScheduleTableFB."Date" ) AS B ON A.date = B.Date 只返回提供的第一个非NULL值。

答案 1 :(得分:1)

@Sagar Galande,这是我建议的代码:

SELECT
      A.[Date]
    , SUM(A.NumberofRegistration) AS NumberofRegistration
    , SUM(A.NumberofCalls) AS NumberofRegistration
FROM
    (
    SELECT
         userprofiles."date" AS [Date],
         COUNT(userprofiles."date") AS NumberofRegistration,
         COUNT(CallScheduleTableFB."Date") AS NumberofCalls
    FROM  
        userprofiles 
            LEFT JOIN 
        CallScheduleTableFB 
            ON userprofiles."date"  = CallScheduleTableFB."Date"  
    GROUP BY  
        userprofiles."date" 
    UNION
    SELECT
         CallScheduleTableFB."Date" AS [Date],
         COUNT(userprofiles."date") AS NumberofRegistration,
         COUNT(CallScheduleTableFB."Date") AS NumberofCalls
    FROM  
        userprofiles 
            RIGHT JOIN 
        CallScheduleTableFB 
            ON userprofiles."date"  = CallScheduleTableFB."Date"  
    GROUP BY  
        CallScheduleTableFB."Date"
    ) AS A
GROUP BY
    A.[Date]