SELECT
    x.[commisionFullNR]
    ,x.commisionName
    ,UPPER(dstatus.dictionaryValue) STATUS
    ,x.[commisionMemo]
    ,x.[commisionOpenDate]
    ,x.[commisionExpectedDate]
    ,total.totalLineQuantity        --Pozycji
    ,total.totalLineQuantityLeft    --Pozostało do rozpisania
FROM [wms].[commision] x
LEFT JOIN (SELECT
        SUM([commisionLineQuantity]) totalLineQuantity
        ,SUM([commisionLineQuantityLeft]) totalLineQuantityLeft
        ,[commisionID]
    FROM [wms].[commisionLine]
    WHERE [status] > -1
    GROUP BY [commisionID]) total
    ON x.commisionid = total.commisionid
LEFT JOIN document.documentType dt
    ON dt.documentType = x.commisionGroupID and dt.documentCategory='commision' -- Uwaga czasem sie powtaraz symbol np w dokuemncie mahazynowym
LEFT JOIN common.dictionary dstatus
    ON x.commisionStatusID = dstatus.dictionaryKeyGuid

WHERE x.status > -1
AND x.commisionStatusID <> '1754E6E7-DD9F-4FD4-868A-9C8FF55D5EB4' -- STATUS ZLECENIA  /*ZAMKNIETE*/
AND x.[commisionGroupID] = 'M'

ORDER BY x.commisionExpectedDate DESC
