1

我有一张显示以前订单的表格。
购买的每件商品都作为单独的行添加到表格中,请参见下面的转储。

我的目标是每月显示每个订单的平均行数。要获得平均行数,我需要将购买的商品数量除以所下订单的数量。

我的查询目前给了我每月的总数,并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');
4

1 回答 1

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;
于 2013-03-21T11:25:00.427 回答