选择不同日期间隔的同一列

时间:2019-04-16 17:15:49

标签: mysql subquery

我正在尝试通过不同的日期间隔和col值从数据库中选择相同的col。

我已经通过此代码尝试过,但是我不知道如何选择具有不同日期间隔的同一个col。

SELECT
    table1.SellerAccount,
    table1.ASIN AS ASIN,
    SELECT AVG(table2.BuyBox) as sevenDaysBack, /* <- 7 days back */
    SELECT AVG(table2.BuyBox) AS twoWeeksBack, /* <- 13 days back */
    SELECT AVG(table2.BuyBox) as oneMonthBack, /* <- 30 days back */
    CURDATE() AS datum
FROM 
    table1
LEFT JOIN 
    table2 ON (table2.ASIN = table1.ASIN)
GROUP BY 
    table1.SellerAccount, table1.ASIN

也通过子查询尝试过,但是对数据分组存在问题。我收到此错误

  

子查询返回1行以上

SELECT
    table1.SellerAccount,
    @ASIN := table1.ASIN AS ASIN,
    (SELECT AVG(table2.BuyBox) FROM table2 
     WHERE table2.DATE > NOW() - INTERVAL 7 DAY AND table2.ASIN = @ASIN 
     GROUP BY SellerAccountId) AS BuyBoxWeekBack,
    (SELECT AVG(table2.BuyBox) FROM table2 
     WHERE table2.DATE > NOW() - INTERVAL 14 DAY AND table2.ASIN = @ASIN 
     GROUP BY SellerAccountId) AS BuyBoxTwoWeekBack,
    (SELECT AVG(table2.BuyBox) FROM table2 
     WHERE table2.DATE > NOW() - INTERVAL 300 DAY AND table2.ASIN = @ASIN 
     GROUP BY SellerAccountId) AS BuyBoxMonthBack,
    CURDATE() AS date
FROM
    table1
GROUP BY 
    table1.SellerAccount, table1.ASIN

我希望输出应返回按SellerAccount和ASIN分组的数据。还有AVG买入框按ASIN和日期间隔进行排序。

0 个答案:

没有答案