我在下面的SQL查询中使用CROSS JOIN
SELECT
store.ACTIVITY_MTH,
Cmps_Util,
SUM(store.Renew) AS GR
FROM
store
CROSS JOIN
(SELECT
SUM(revenue.rev_attained) * 100 AS Cmps_Util
FROM
revenue
WHERE revenue.start_date BETWEEN '2014-05-01' AND '2014-10-31'
AND revenue.metric_id = 182
AND revenue.id = 'PH') AS Cmps_Util
WHERE
AND store.ACTIVITY_MTH BETWEEN '2014-05-01' AND '2014-10-31'
GROUP BY store.ACTIVITY_MTH
这导致以下回复
ACTIVITY_MTH Cmps_Util GR
2014-05-01 1.2362 356
2014-06-01 1.2362 789
2014-07-01 1.2362 45
2014-08-01 1.2362 1567
2014-09-01 1.2362 45
2014-10-01 1.2362 786
请注意,列Cmps_Util
的所有值都相同。这是Cross Joined
列。我怎么能阻止它重复?注意GR列不重复数据。基本上我希望特定月份的Cmps_Util中的数据与Activity_MTH
列对齐。 (Revenue
表也有revenue.start_date
,用于Cmps_Util)。如果收入表没有该月的条目,则NULL
如下所示。
ACTIVITY_MTH Cmps_Util GR
2014-05-01 null 356
2014-06-01 2.523 789
2014-07-01 null 45
2014-08-01 1.2362 1567
2014-09-01 1.6 45
2014-10-01 1.86 786
答案 0 :(得分:0)
请勿使用CROSS JOIN
。我相信你只想在这里找到一个无聊的旧LEFT JOIN
,但是你的子查询需要包含子查询中每个Revenue.start_date
的月初,以便它可以加入Activity_Mth
SELECT store.ACTIVITY_MTH,
SUM(Cmps_Util.Cmps_Util),
SUM(store.Renew) AS GR
FROM store
LEFT JOIN
(
SELECT FIRST_DAY(revenue.start_date) AS start_date_month,
SUM(revenue.rev_attained) * 100 AS Cmps_Util
FROM revenue
WHERE revenue.start_date BETWEEN '2014-05-01'
AND '2014-10-31'
AND revenue.metric_id = 182
AND revenue.id = 'PH'
GROUP BY 1
) AS Cmps_Util
ON store.ACTIVITY_MTH = Cmps_Util.start_date_month
GROUP BY store.ACTIVITY_MTH
问题在于,CROSS JOIN
将为您提供Cmps_Util
的每个值以及来自store
的每个值在每个可能的组合中连接在一起。相反,您希望加入revenue
表中Activit_mth
表的store
表的月份/日期(我假设)。
答案 1 :(得分:0)
听起来你需要离开连接2个派生表。第一个派生表将包含每个activity_mth的gr
总和,第二个将包含每个Cmps_Util
的{{1}}总和(假设您的所有start_date
值都在第1个像activity_mth这样的月份 - 否则你需要从start_date中提取第一天。
start_date