0

我总共需要使用四 (4) 个表。本质上,一个从另一个拉取数据,从另一个拉取数据以获取以前的表数据,依此类推。

我无法获得将成功运行而不会超时的查询。我想显示商品的SUMofVISITS及其在给定时间段内的总ORDER销售额MONTH

表结构

table1 (WebVisits)
ID   DATE        WEBNUMBER  VISITS
1    2012-01-01  apw-rtr8   2
..   ...         ...        ..


table2 (Commodities)
ID      WEBNUMBER   TIER1
5791    apw-rtr8    Refrigeration
..      ...         ...


table3 (Attributes)
ITEM        WEB_NUM
APW-RTR-8   apw-rtr8
..          ...


table4 (SalesData)
ID     ITEM        QUANTITY  UNIT_PRICE  TRANS_DATE
31905  APW-RTR-8   1         1522.38     2012-02-05
..     ...         ...       ...         ...

SELECT 
    MONTH(t1.DATE) AS MONTH, 
    SUM(t1.VISITS) as Visits,
    t2.TIER1 as Category
FROM
    table1 t1
        LEFT JOIN
    table2 t2 ON t1.WEBNUMBER = t2.WEBNUMBER
        LEFT JOIN
    table3 t3 ON t2.WEBNUMBER = t3.WEB_NUM
WHERE
    t1.DATE BETWEEN '2012-01-01' AND '2012-05-31'
        AND t3.TIER1 = 'Cooking Equipment '
        AND EXISTS( SELECT 
            sum(t4.UNIT_PRICE * t4.QUANTITY) as total
        FROM
            table4 t4
        WHERE
            t4.ITEM = t3.ITEM
                AND t4.TRANS_DATE BETWEEN '2012-01-01' AND '2012-05-31')
GROUP BY MONTH
ORDER BY MONTH

基本上类别 (TIER1) 将是已知的并且日期范围将是已知的。鉴于上面的查询,我希望它吐出与此类似的结果:

MONTH   Visits  Total     Category
1       4054    32058.08  Cooking Equipment 
2       3564    28116.17  Cooking Equipment 
3       4514    25819.66  Cooking Equipment 
4       3621    18732.96  Cooking Equipment 
5       6521    55378.11  Cooking Equipment 
4

1 回答 1

2

我开始编写查询并意识到我编写的查询与您编写的几乎相同。

确保indexes存在以下内容:

table1.DATE
table1.WEBNUMBER
table2.WEBNUMBER
table3.WEB_NUM
table4.ITEM
table4.TRANS_DATE

编辑:

试试这个:

SELECT 
    MONTH(table1.DATE) AS MONTH, 
    SUM(table1.VISITS) as Visits, 
    table2.TIER1 as Category, 
    SUM(table4.UNIT_PRICE * table4.QUANTITY) 
FROM table1 
LEFT JOIN table2 USING(WEBNUMBER) 
LEFT JOIN table3 table1.WEBNUMBER = table3.WEB_NUM 
LEFT JOIN table4 table1.WEBNUMBER = table4.ITEM 
WHERE table2.TIER1 = 'Cooking Equipment' 
AND table4.TRANS_DATE BETWEEN '2012-01-01' 
AND '2012-05-31' 
GROUP BY MONTH 
ORDER BY MONTH
于 2012-12-05T15:50:52.350 回答