这里我要返回所有案例的总和。我的要求是了解特定产品是否在过去10周内销售。对于每周,当它在一周内销售时返回1或在没有任何销售时返回0。因此,如果一个产品在过去10周内都有销售,那么无论销售数量多少,我都必须返回10。但使用下面的查询,我得到的销售数量。
选择查询:
SELECT PartNo
, sum(CASE WHEN DocDate BETWEEN "2017-01-26" AND "2017-02-01" THEN 1 ELSE 0 END
+ CASE WHEN DocDate BETWEEN "2017-02-02" AND "2017-02-08" THEN 1 ELSE 0 END) as Qty1
FROM (`tbl_sales2`)
GROUP
BY `PartNo`
ORDER
BY `Qty1` DESC;
结果:
+-------------+------+
| PartNo | Qty1 |
+-------------+------+
| 09343M05068 | 6 |
| 09343M05069 | 3 |
| 09343M05070 | 2 |
+-------------+------+
3 rows in set (0.00 sec)
预期结果:
+-------------+------+
| PartNo | Qty1 |
+-------------+------+
| 09343M05068 | 2 |
| 09343M05069 | 2 |
| 09343M05070 | 1 |
+-------------+------+
表格查询:
CREATE TABLE IF NOT EXISTS `tbl_sales2` (
`SaleId` int(11) NOT NULL AUTO_INCREMENT,
`DocDate` date NOT NULL,
`PartNo` varchar(20) NOT NULL,
PRIMARY KEY (`SaleId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
示例数据:
INSERT INTO `tbl_sales2` (`SaleId`, `DocDate`, `PartNo`) VALUES
('1', '2017-01-26', '09343M05068'),
('2', '2017-01-27', '09343M05068'),
('3', '2017-01-28', '09343M05068'),
('4', '2017-01-29', '09343M05068'),
('5', '2017-01-28', '09343M05069'),
('6', '2017-01-29', '09343M05069'),
('7', '2017-02-02', '09343M05068'),
('8', '2017-02-03', '09343M05068'),
('9', '2017-02-02', '09343M05069'),
('10', '2017-02-02', '09343M05070'),
('11', '2017-02-02', '09343M05070');
答案 0 :(得分:0)
如果MAX
的给定日期范围内至少有一行,请使用SUM
代替PartNo
获取1:
select PartNo,
max(case when DocDate between '2017-01-26'
and '2017-02-01' then 1 else 0 end)
+ max(case when DocDate between '2017-02-02'
and '2017-02-08' then 1 else 0 end) as Qty1
from `tbl_sales2`
group by `PartNo`
order by `Qty1` desc;
产地:
PartNo Qty1
09343M05068 2
09343M05069 2
09343M05070 1