连接两个表并获取聚合数据

时间:2010-04-16 20:17:08

标签: sql

如何编写一个查询,返回过去x个月内加利福尼亚的汇总销售数据。

 -----------------------        -----------------------
|         order         |      |       customer        |
|-----------------------|      |-----------------------|
| orderId       int     |      | customerId     int    |
| customerId    int     |      | state         varchar |
| deposit       decimal |       -----------------------
| orderDate     date    |   
 ----------------------- 


                  ----------------------- 
                 |      orderItem        |
                 |-----------------------|
                 | orderId      int      |
                 | itemId       int      |
                 | qty          int      |
                 | lineTotal    decimal  |
                 | itemPrice    decimal  |
                  ----------------------- 

1 个答案:

答案 0 :(得分:1)

假设您正在查找位于qty的所有orderItem ordercustomer的{​​{1}}总计'CA'(如果您需要)总结其他字段,修改查询不应该太难:

SELECT
    SUM(oi.qty) as TotalQuantitySold
FROM
    orderItem oi
    INNER JOIN order o
        ON oi.orderId = o.orderId
    INNER JOIN customer c
        ON o.customerId = c.customerId
WHERE
    c.state = 'CA'
    AND DATEDIFF(month, o.orderDate, <some fixed date>)

DATEDIFF来自T-SQL,计算日期差异可能取决于您的平台

相关问题