如何编写一个查询,返回过去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 :(得分:1)
假设您正在查找位于qty
的所有orderItem
order
位customer
的{{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,计算日期差异可能取决于您的平台