Назад | Перейти на главную страницу

Запрос MS SQL Сумма подзапроса

Мне нужна помощь, я получаю следующий результат запроса.

SELECT
      ARG_CONSUMER,
      cast(ARG_TOTALAMT as float)/100 AS 'Total',
      (SELECT SUM(cast(DAMT as float))/100 FROM DEBT WHERE DDATE >= ARG.ARG_ORIGDATE AND DDATE <= ARG.ARG_LASTPAYDATE AND DTYPE IN ('CSH','CNTP','DDR','NBP') AND DCONSUMER = ARG.ARG_CONSUMER
        ) AS 'Paid'
FROM
     ARGMASTER ARG
WHERE ARG_STATUS = '1'

Текущий вывод - это список всех записей ...

Но я хочу достичь здесь

count of arg consumers
Total of ARG_TOTALAMT
total of that subquery  PAID
difference between PAID & Total amount.

Я могу достичь первых двух, то есть подсчета потребителей и общего ARG _ TOTALAMT ... но я смущен суммой ... т.е.

sum (SELECT SUM(cast(DAMT as float))/100 FROM DEBT WHERE DDATE >= ARG.ARG_ORIGDATE AND DDATE <= ARG.ARG_LASTPAYDATE AND DTYPE IN ('CSH','CNTP','DDR','NBP') AND DCONSUMER = ARG.ARG_CONSUMER) AS 'Paid'

Пожалуйста посоветуй

Изменение подзапроса на ВНЕШНЕЕ ПРИЛОЖЕНИЕ

SELECT
      COUNT(DISTINCT ARG_CONSUMER) AS [count of arg consumers],
      cast(ARG_TOTALAMT as float)/100 AS [Total],
      foo.Paid,
      cast(ARG_TOTALAMT as float)/100 - foo.Paid AS [difference between PAID & Total amount]
FROM
     ARGMASTER ARG
     OUTER APPLY
     (
     SELECT
         SUM(cast(D.DAMT as float))/100 AS Paid
     FROM DEBT D
     WHERE
          DDATE >= ARG.ARG_ORIGDATE AND D.DDATE <= ARG.ARG_LASTPAYDATE
          ANDD. DTYPE IN ('CSH','CNTP','DDR','NBP') AND D.DCONSUMER = ARG.ARG_CONSUMER
     ) foo
WHERE ARG.ARG_STATUS = '1'