2010-04-16 43 views
0

我該如何編寫一個查詢,該查詢返回過去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 | 
        ----------------------- 
+0

你嘗試過什麼?對於什麼數據庫?我很少看到使用格式設置的全新帳戶帖子... – 2010-04-16 20:19:15

+0

您希望聚合什麼?總銷售額,客戶訂單數量,總存款數量,銷售的總數量? – TLiebe 2010-04-16 20:20:08

+0

我喜歡格式! :) – Kiril 2010-04-16 22:54:09

回答

1

假設你正在尋找總數的qty對所有order s的位於'CA'customer s分別orderItem(如果你想總結等領域,應該不會太難修改查詢):

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,以及計算的時間差可能取決於你的平臺上

+0

教魚,不發魚。 – Broam 2010-04-16 20:22:19

+0

對於從具體的答案中學習,還有些東西需要說明。他是一個全新的用戶,所以我削減了他一些鬆懈。 – 2010-04-16 20:41:51