我有一张表格显示以前的订单 购买的每件商品都会在表格中添加为单独的行,请参阅下面的转储。
我的目标是每月显示每个订单的平均线数。 为了获得平均线数,我需要将所购买的商品数量除以所下订单量。
我的查询目前为我提供了每月总计,而line_count
返回了正确购买的商品数量,但我似乎无法返回已下订单的数量(在下面的转储中应该给出13)。我试过添加各种子查询,但我不知道该怎么做。有什么想法吗?
SELECT
date,
COUNT(orderno) AS line_count
FROM `orders`
AND
date BETWEEN '2010-01-21' AND CURDATE()
GROUP BY month(date), year(date)
ORDER BY date
这是表格模式(为简洁起见而简化)
CREATE TABLE IF NOT EXISTS `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`orderno` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
`date` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=22904 ;
--
-- Dumping data for table `orders`
--
INSERT INTO `orders` (`id`, `orderno`, `date`) VALUES
(1, 'rad10000', '2010-01-21'),
(2, 'rad10000', '2010-01-21'),
(3, 'rad10001', '2010-01-21'),
(4, 'rad10001', '2010-01-21'),
(5, 'rad10002', '2010-01-21'),
(6, 'rad10003', '2010-01-21'),
(8, 'rad10003', '2010-01-21'),
(9, 'rad10003', '2010-01-21'),
(10, 'rad10004', '2010-01-22'),
(11, 'rad10004', '2010-01-22'),
(12, 'rad10005', '2010-01-22'),
(13, 'rad10005', '2010-01-22'),
(14, 'rad10006', '2010-01-22'),
(15, 'rad10007', '2010-01-22'),
(16, 'rad10008', '2010-01-22'),
(17, 'rad10009', '2010-01-22'),
(18, 'rad10010', '2010-01-22'),
(19, 'rad10011', '2010-01-22'),
(20, 'rad10012', '2010-01-22');
答案 0 :(得分:2)
哦,我明白了......
SELECT YEAR(date)
, MONTH(date)
, COUNT(*) line_count
, COUNT(DISTINCT orderno) orders_placed
FROM orders
WHERE date BETWEEN '2010-01-21' AND CURDATE()
GROUP
BY YEAR(date)
, MONTH(date)
ORDER
BY date;