我正在寻找一种方法来计算等于组的最小值或最大值的项目数。我有每隔几天收到的物品,每两周输入一次。我需要查看每个EntryDate的Min和Max ReceivedDate,以及Min和Max处的项目数。在MS Access中使用SQL。
tblItem
| EntryDate | ReceivedDate |
--------------------------------------
| 01/01/2016 | 16/12/2015 |
| 01/01/2016 | 15/12/2015 |
| 01/01/2016 | 10/12/2015 |
| 01/01/2016 | 10/12/2015 |
| 01/01/2016 | 10/12/2015 |
| 01/01/2016 | 10/12/2015 |
| 15/01/2016 | 05/01/2016 |
| 15/01/2016 | 05/01/2016 |
| 15/01/2016 | 04/01/2016 |
| 15/01/2016 | 03/01/2016 |
| 15/01/2016 | 03/01/2016 |
| 15/01/2016 | 03/01/2016 |
SELECT tblItem.EntryDate,
Min(tblItem.ReceivedDate) AS MinReceivedDate,
Max(tblItem.ReceivedDate) AS MaxReceivedDate
FROM tblItem
GROUP BY tblItem.EntryDate;
Query1
| EntryDate | MinReceivedDate | MaxReceivedDate |
--------------------------------------------------
| 01/01/2016 | 10/12/2015 | 16/12/2015 |
| 15/01/2016 | 03/01/2016 | 05/01/2016 |
Query1
| EntryDate | MinReceivedDate | CountOfMin | MaxReceivedDate | CountOfMax |
---------------------------------------------------------------------------
| 01/01/2016 | 10/12/2015 | 4 | 16/12/2015 | 1 |
| 15/01/2016 | 03/01/2016 | 3 | 05/01/2016 | 2 |
答案 0 :(得分:4)
我不知道MS Access是否允许这样的子查询。如果这不起作用,请告诉我,我将删除答案。否则:
SELECT
SQ.EntryDate,
SQ.MinReceivedDate,
SUM(IIF(I.ReceivedDate = SQ.MinReceivedDate, 1, 0)) AS CountOfMin,
SQ.MaxReceivedDate,
SUM(IIF(I.ReceivedDate = SQ.MaxReceivedDate, 1, 0)) AS CountOfMax
FROM (
SELECT
SQI.EntryDate,
MIN(SQI.ReceivedDate) AS MinReceivedDate,
MAX(SQI.ReceivedDate) AS MaxReceivedDate
FROM
tblItem SQI
GROUP BY
SQI.EntryDate
) SQ
INNER JOIN tblItem I ON I.EntryDate = SQ.EntryDate
GROUP BY
SQ.EntryDate,
SQ.MinReceivedDate,
SQ.MaxReceivedDate