使用SQL显示组内的最小计数和最大计数

时间:2016-02-23 19:56:16

标签: sql ms-access correlated-subquery

目标

我正在寻找一种方法来计算等于组的最小值或最大值的项目数。我有每隔几天收到的物品,每两周输入一次。我需要查看每个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     |

1 个答案:

答案 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