Search code examples
sqlms-accesscorrelated-subquery

Use SQL to display count of min and count of max within group


Goal

I am looking for a way to count the number of items that are equal to the min or max of a group. I have items that are received every few days and are entered bi-weekly. I need to see the Min and Max ReceivedDate for each EntryDate, and the Count of items at the Min and at the Max. Using SQL in MS Access.

Input

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    |

Current Query

SELECT tblItem.EntryDate, 
Min(tblItem.ReceivedDate) AS MinReceivedDate, 
Max(tblItem.ReceivedDate) AS MaxReceivedDate
FROM tblItem
GROUP BY tblItem.EntryDate;

Current Output

Query1

| EntryDate  | MinReceivedDate | MaxReceivedDate |
--------------------------------------------------
| 01/01/2016 |    10/12/2015   |   16/12/2015    |
| 15/01/2016 |    03/01/2016   |   05/01/2016    |

Desired Output

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     |

Solution

  • I don't know if MS Access allows subqueries like this. If this doesn't work, please let me know and I'll delete the answer. Otherwise though:

    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