我有以下sql查询:
SELECT
a.url,
b.lpvs,
a.volume,
a.sales_usd,
a.sales_eur,
a.sales_gbp,
a.sales_jpy
FROM (
SELECT
referer_trackings.cookie_first_url AS url,
count(purchases.id) AS volume,
SUM(CASE WHEN purchases.currency = 'USD' THEN purchases.price ELSE 0 END) AS sales_usd,
SUM(CASE WHEN purchases.currency = 'EUR' THEN purchases.price ELSE 0 END) AS sales_eur,
SUM(CASE WHEN purchases.currency = 'GBP' THEN purchases.price ELSE 0 END) AS sales_gbp,
SUM(CASE WHEN purchases.currency = 'JPY' THEN purchases.price ELSE 0 END) AS sales_jpy
FROM purchases
JOIN referer_trackings
ON referer_trackings.trackable_id = purchases.id
JOIN items
ON purchases.item_id = items.id
WHERE items.seller_id = '6'
AND referer_trackings.trackable_type = 'Purchase'
AND purchases.workflow_state = 'payment_successful'
GROUP BY referer_trackings.cookie_first_url
ORDER BY volume DESC
) AS a, (SELECT
count(referer_trackings.id) AS lpvs
FROM referer_trackings
JOIN product_landing_page_views
ON product_landing_page_views.id = referer_trackings.trackable_id
JOIN items
ON items.id = product_landing_page_views.item_id
WHERE referer_trackings.trackable_type = 'ProductLandingPageView'
AND items.seller_id = '6')
AS b
这产生了这个结果:
url lpvs volume sales_usd sales_eur sales_gbp sales_jpy
=======================================================================
url1 1082 3 9.99 9.99 9.99 0.0
url2 1082 1 0.0 9.99 0.0 0.0
^
lpvs列的第二行(值:1082,下面带有小箭头)应为0,而不是1082.值1082仅对第一行正确。
我知道这是因为加入/选择时加倍了但我似乎无法解决这个问题并使查询恰到好处。
我可以从我的ruby代码中调用两个查询并合并结果。这将是快速解决方案。但是,我想保持这个清洁,并寻求一个纯粹的SQL解决方案。我觉得我非常接近。
如果有人知道如何使用ActiveRecord做到这一点,那也很好: - )。
谢谢你的时间!
=====编辑=====
基于Rahul的调整,这是查询的结果:
url lpvs volume sales_usd sales_eur sales_gbp sales_jpy
=======================================================================
url1 7 7 19.98 29.97 19.98 0.0
url2 1 1 0.0 9.99 0.0 0.0
^ ^ ^ ^ ^
^1, row 1 => value should be 1082
^1, row 2 => value should be 0
^2, row 1 => value should be 3
^2, row 2 => value should be 1
^3, row 1 => value should be 9.99 (current value is doubled somehow)
^4, row 1 => value should be 9.99 (current value is tripled somehow)
^5, row 1 => value should be 9.99 (current value is doubled somehow)
答案 0 :(得分:0)
那是因为你在查询部分下面的虚假信息,我不知道你为什么这么做......
fread()
在您的主要选择中,您正在说
....
ORDER BY volume DESC
) AS a, (SELECT
count(referer_trackings.id) AS lpvs
FROM referer_trackings
........)
AS b
是的,将整个查询修改为如下所示
SELECT
a.url,
b.lpvs, <-- result of above posted query part