小编典典

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

sql

目标

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

阅读 239

收藏
2021-05-23

共1个答案

小编典典

我不知道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
2021-05-23