我将以下两张表作为订单处理系统的一部分:
order(id, date)
order_item(order_id, item_id, type)
类型是一个枚举,表示查看order_item的表。
我想编写一个查询,选择每天订购的不同商品类型的数量。所以它应该产生类似的东西:
Date tshirts dvds mugs cds
07/07/2010 3 6 2 2
10/07/2010 4 9 3 1
13/07/2010 1 2 1 9
以下是我目前必须为一种类型选择计数的查询。我只是无法解决如何扩展它以选择多种类型的计数。
SELECT DATE(order.date), COUNT(order.date)
FROM order, order_item
WHERE order.id = order_item.order_id AND order_item.type = 'tshirts'
GROUP BY DATE(order.date)
答案 0 :(得分:1)
听起来像SQL Server PIVOT
命令的情况:
http://msdn.microsoft.com/en-us/library/ms177410.aspx
要做到这一点有点棘手,但通过一些实验,你应该根据需要得到你的结果。
答案 1 :(得分:1)
您不应使用逗号语法进行连接。使用可以缩写为JOIN的INNER JOIN关键字的ISO语法。
Select O.Date
, Sum( Case When OI.Type = 'tshirts' Then 1 Else 0 End ) As tshirts
, Sum( Case When OI.Type = 'dvds' Then 1 Else 0 End ) As dvds
, Sum( Case When OI.Type = 'mugs' Then 1 Else 0 End ) As mugs
, Sum( Case When OI.Type = 'cds' Then 1 Else 0 End ) As cds
From Order As O
Join Order_Item As OI
On OI.order_id = O.id
Where OI.type In('tshirts','dvds','mugs','cds')
Group By O.Date
答案 2 :(得分:0)
它不会给你你想要的东西
SELECT DATE(order.date), COUNT(order_item.type) as count , order_item.type as type
FROM order, order_item
WHERE order.id = order_item.order_id AND order_item.type = 'tshirts'
GROUP BY DATE(order.date), order_item.type
它将提供类似下面的内容
Date type count
07/07/2010 tshirts 3
07/07/2010 dvds 6
07/07/2010 mugs 2
07/07/2010 cds 2
10/07/2010 tshirts 4
10/07/2010 dvds 9
10/07/2010 mugs 3
10/07/2010 cds 1
13/07/2010 tshirts 1
13/07/2010 dvds 2
13/07/2010 mugs 1
13/07/2010 cds 9
我知道的两个缺点是
答案 3 :(得分:0)
这对我有用(使用MySQL):
SELECT o.date, COUNT(if(oi.type='tshirts', 1, NULL)) as tshirts, COUNT(if(oi.type='mugs', 1, NULL)) as mugs
FROM order_item oi LEFT JOIN order o ON oi.order_id = o.id
GROUP BY o.date
答案 4 :(得分:0)
以下是我最终使用的查询:
SELECT DATE(order.date) AS day,
(SELECT COUNT(order.date)
FROM order, order_item
WHERE DATE(order.date) = day AND
order.id = order_item.order_id AND
order_item.type = 'tshirt') AS tshirt,
(SELECT COUNT(order.date)
FROM order, order_item
WHERE DATE(order.date) = day AND
order.id = order_item.order_id AND
order_item.type = 'mugs') AS mugs,
etc.
FROM order
GROUP BY DATE(order.date)
这是非常缓慢的,但它确实起到了作用。