sqlsql-servercalculated-columns

Calculate quantity based on column from a different table


I currently am working with 2 tables tbRecords and tbInspectedParts. tbRecord has an auto increment column that is mapped back to the tbInspectionParts through column eRecordId.

Example - tbRecord:

id Status QTY Part
7998 Closed 10 7845

tbInspectedParts:

id eRecordId Disposition
1 7998 4
2 7998 5
3 7998 2
4 7998 2
5 7998 1
6 7998 3
7 7998 4
8 7998 3
9 7998 3
10 7998 1

I am current running the query

SELECT 
    tbInspectedParts.eMRBRecord,
    tbInspectedParts.Disposition,
    QTY, Part
FROM 
    [mrbDB].[dbo].[tbRecords] 
INNER JOIN 
    tbInspectedParts ON tbRecords.id = tbInspectedParts.eMRBRecord
WHERE 
    tbRecords.id = 7998

Which is returning this result:

eRecordId Disposition QTY Part
7998 4 10 7845
7998 5 10 7845
7998 2 10 7845
7998 2 10 7845
7998 1 10 7845
7998 3 10 7845
7998 4 10 7845
7998 3 10 7845
7998 3 10 7845
7998 3 10 7845

This is taking the value of tbRecord.QTY which is correct because 10 parts were inspected from record 7998 but there are different disposition which I would like to quantify in a column.

Example:

eRecordId Disposition QTY Part
7998 4 2 7845
7998 5 1 7845
7998 2 2 7845
7998 1 1 7845
7998 3 4 7845

Solution

  • You can group by all the selected columns and then count the records

    SELECT
        eRecordId,
        Disposition, 
        COUNT(*) AS QTY,
        Part
    FROM [mrbDB].[dbo].[tbRecords] 
    INNER JOIN tbInspectedParts
        ON tbRecords.id = tbInspectedParts.eRecordId
    WHERE tbRecords.id = 7998
    GROUP BY eRecordId, Disposition, Part
    ORDER BY Disposition
    

    The rule is that all the columns in the select list not being aggregated must be listed in the GROUP BY clause. You can apply aggregate functions like SUM, COUNT, MIN, MAX or AVG and many more to the aggregated columns.

    If you don't add an ORDER BY clause, the order is unpredictable.

    See: https://sqlfiddle.com/sql-server/online-compiler?id=75eeaa43-9fb0-44f3-bcfa-23f8443cb53f