如何组合来自同一连接表的两个sql计数

时间:2016-11-03 19:15:17

标签: mysql

另一个讨厌的学生在这里! 今天我花了几个小时尝试在单个表输出中组合(选择)2个已加入的SQL输出+原始表的ID。最终导致了这个问题:

SELECT * FROM(
SELECT fd1.User_idUser,avg(fd1.caloryIntake) 
AS 'workdays'
FROM fact_dailysnapshot fd1
INNER JOIN dim_day dd1 ON dd1.DATE_SK = fd1.DATE_SK
WHERE dd1.weekend_ind = 'N'
GROUP BY fd1.User_idUser 
ORDER BY fd1.User_idUser) A,

(SELECT avg(fd1.caloryIntake) AS 'weekend'
FROM fact_dailysnapshot fd1
INNER 
JOIN dim_day dd1 ON dd1.DATE_SK = fd1.DATE_SK
WHERE dd1.weekend_ind = 'Y'
GROUP BY fd1.User_idUser 
ORDER BY fd1.User_idUser) B;

这转化为...
output

现在这是一个错误的结果,第二列为所有用户条目提供了几乎恒定的值。我认为这必须通过某种EXTRA加入来解决,但我确实没有想法。在此先感谢..!

2 个答案:

答案 0 :(得分:1)

您的JOIN缺少与ON相关联的User_idUser条款。

但是,编写查询的最简单方法是使用条件聚合:

SELECT fd1.User_idUser,
       avg(case when dd1.weekend_ind = 'N' then fd1.caloryIntake end) as weekday_avg,
       avg(case when dd1.weekend_ind = 'Y' then fd1.caloryIntake end) as weekend_avg
FROM fact_dailysnapshot fd1 INNER JOIN
     dim_day dd1
     ON dd1.DATE_SK = fd1.DATE_SK
GROUP BY fd1.User_idUser 
ORDER BY fd1.User_idUser;

这是一个查询,而不是两个。

答案 1 :(得分:0)

如果我理解正确,这就是你要找的东西:

SELECT A.User_idUser, A.workdays, B.weekend 

FROM (

    SELECT fd1.User_idUser, avg(fd1.caloryIntake) AS 'workdays'
    FROM fact_dailysnapshot fd1
    INNER JOIN dim_day dd1 
       ON dd1.DATE_SK = fd1.DATE_SK
    WHERE dd1.weekend_ind = 'N'
    GROUP BY fd1.User_idUser 
    ORDER BY fd1.User_idUser) A

JOIN 
    (SELECT fd1.User_idUser, avg(fd1.caloryIntake) AS 'weekend'
    FROM fact_dailysnapshot fd1
    INNER JOIN dim_day dd1 
       ON dd1.DATE_SK = fd1.DATE_SK
    WHERE dd1.weekend_ind = 'Y'
    GROUP BY fd1.User_idUser 
    ORDER BY fd1.User_idUser) B

    ON A.User_idUser = B.User_idUser

每个查询都会按ID及其工作日或周末为您提供所有用户。您需要在用户ID上加入两个查询的结果。