AXForum  
Вернуться   AXForum > Microsoft Dynamics AX > DAX: Программирование
All
Забыли пароль?
Зарегистрироваться Правила Справка Пользователи Сообщения за день Поиск

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 27.02.2013, 12:33   #1  
user_ax is offline
user_ax
Участник
Аватар для user_ax
 
599 / 39 (3) +++
Регистрация: 07.10.2012
Адрес: ZP
:( Условия в запросе sql в аксапте
Поставлена задача модифицировать запрос, который генерирует отчёт Свод дебиторской/кредиторской задолженности.
Нужно, если выборка идёт из журнала накладных(LedgerjournalTable.JournalType = 10), вместо поля RcontractAccount выводить поле LedgerJournalTrans.PaymPurpose_ZTR.

Нашёл класс, который генерирует этот отчёт. В создании отчёта(createdQuery), где есть большой запрос, который, я так понимаю, и генерирует сам отчёт, нашёл блок с условиями и добавил туда свои условия. Проблема в том, что если моё условие добавить в конец блока, метод возвращает false и отчёт не создаётся(будет throw), а если условие поставить посредине блока - пишет. что неверное названия поля PaymPurpose_ZTR. Но! Такое поле есть, проверено.
Подскажите пожалуйста, в какую сторону копать. Вроде такая простая задача и столько стопоров...первый раз просто столкнулся с sql -запросами в аксапте подобного вида..

Условие:

X++:
 case
            when SubjectOfAgreement_ZTR != '' then SubjectOfAgreement_ZTR
            when (LedgerjournalTrans.BankCentralBankPurposeText is not null and LedgerjournalTrans.BankCentralBankPurposeText != '' and  Journaltype = 4)
                then LedgerjournalTrans.BankCentralBankPurposeText
                  --->3780 26.02.2013
          when (LedgerJournalTable.Journaltype = 10 and LedgerjournalTrans.PaymPurpose_ZTR is not null)
           then LedgerjournalTrans.PaymPurpose_ZTR
          --<-
            when (LedgerjournalTrans.Txt is not null and LedgerjournalTrans.Txt != '' and (Journaltype = 0 or Journaltype = 45))
                then custtrans.Txt
            when (substring(rContractTable.RContractSubject,1,1000) is not null and substring(rContractTable.RContractSubject,1,1000) != '')  then substring(rContractTable.RContractSubject,1,1000)

            else ''
        end as RContractSubject,
" + @"
это в select, ниже ещё insert есть

X++:
case
            when SubjectOfAgreement_ZTR != '' then SubjectOfAgreement_ZTR
                  --->3780 26.02.2013
         when (LedgerJournalTable.Journaltype = 10 and LedgerjournalTrans.PaymPurpose_ZTR is not null)
         then LedgerjournalTrans.PaymPurpose_ZTR
          --<-
            when (LedgerjournalTrans.Txt is not null and LedgerjournalTrans.Txt != '' /*and (Journaltype = 0 or Journaltype = 45)*/)
                then custtrans.Txt
            when (substring(rContractTable.RContractSubject,1,1000) is not null and substring(rContractTable.RContractSubject,1,1000) != '')  then substring(rContractTable.RContractSubject,1,1000)

            else ''
        end as RContractSubject,
DAX 2009, 5.0.1500, ,SQL Server 2008.

Буду благодарен за любые ответы.
Старый 27.02.2013, 12:35   #2  
user_ax is offline
user_ax
Участник
Аватар для user_ax
 
599 / 39 (3) +++
Регистрация: 07.10.2012
Адрес: ZP
В join-ах ещё пытался добавить свой номер журнала, но тогда тоже ругается, что такого поля не знает...а если не добавлять - отчёт не содержит данных...

кусок кода из select-a
X++:
 inner join LedgerjournalTable on LedgerjournalTrans.journalnum = LedgerjournalTable.journalnum and posted = 1
            and Journaltype in(0, 4,  45)  and LedgerjournalTrans.dataareaid = '" + dataAreaId + @"'
из insert-a
X++:
   left join LedgerjournalTable on LedgerjournalTrans.journalnum = LedgerjournalTable.journalnum and posted = 1
            and Journaltype in(0, 7, 45) and LedgerjournalTable.dataareaid = '" + dataAreaId + @"'
Старый 27.02.2013, 12:38   #3  
user_ax is offline
user_ax
Участник
Аватар для user_ax
 
599 / 39 (3) +++
Регистрация: 07.10.2012
Адрес: ZP
И ошибка вылазит временами, только что откомпилировал - опять кричит, что поле не найдено. Хотя минут 10 назад говорило, что отчёт не содержит данных...
Старый 27.02.2013, 12:40   #4  
S.Kuskov is offline
S.Kuskov
Участник
Лучший по профессии 2017
Лучший по профессии 2015
Лучший по профессии 2014
 
3,429 / 1772 (66) ++++++++
Регистрация: 28.04.2007
Адрес: Калуга
Пальцем в небо. Поле PaymPurpose_ZTR точно есть в таблице в самой базе данных. Потому что, если проверялось только его наличие в таблице в AOT, то это ещё ничего не значит. Поле может быть выключено кофигурационным ключом.
Старый 27.02.2013, 12:42   #5  
user_ax is offline
user_ax
Участник
Аватар для user_ax
 
599 / 39 (3) +++
Регистрация: 07.10.2012
Адрес: ZP
Цитата:
Сообщение от S.Kuskov Посмотреть сообщение
Пальцем в небо. Поле PaymPurpose_ZTR точно есть в таблице в самой базе данных. Потому что, если проверялось только его наличие в таблице в AOT, то это ещё ничего не значит. Поле может быть выключено кофигурационным ключом.
Да, согласен, полную картину не описал.
Проверил запросом через sqlmanagmentstudio - поле есть.


Это ведь прямой sql запрос, на него не распространяются ключи.

Последний раз редактировалось user_ax; 27.02.2013 в 12:45.
Старый 27.02.2013, 12:53   #6  
S.Kuskov is offline
S.Kuskov
Участник
Лучший по профессии 2017
Лучший по профессии 2015
Лучший по профессии 2014
 
3,429 / 1772 (66) ++++++++
Регистрация: 28.04.2007
Адрес: Калуга
Полный запрос в sqlmanagmentstudio выполняется?
Старый 27.02.2013, 13:04   #7  
user_ax is offline
user_ax
Участник
Аватар для user_ax
 
599 / 39 (3) +++
Регистрация: 07.10.2012
Адрес: ZP
Цитата:
Сообщение от S.Kuskov Посмотреть сообщение
Полный запрос в sqlmanagmentstudio выполняется?
увы, не знаю, первый раз столкнулся с подобным запросом, сейчас пытаюсь выполнить в sqlmanagmentstudio, ошибок в синтаксисе куча.
Старый 27.02.2013, 14:59   #8  
user_ax is offline
user_ax
Участник
Аватар для user_ax
 
599 / 39 (3) +++
Регистрация: 07.10.2012
Адрес: ZP
Без моих модификаций запрос отрабатывает, с моими - ругается. Буду разбираться, в чём причина.
Старый 27.02.2013, 15:19   #9  
user_ax is offline
user_ax
Участник
Аватар для user_ax
 
599 / 39 (3) +++
Регистрация: 07.10.2012
Адрес: ZP
Весело, однако...

В sql даже не видит нужного мне поля, хотя я его выбрал из предложенного выпадающего списка!
А после того, как я добавил поле в группировку, мне выдало вот такую ошибку:

X++:
Msg 306, Level 16, State 2, Line 235
The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.
На сколько я понял, типы текст, нтекст и изображения не могут поддаваться группировке.
Убрал из своего условия is null - ошибка осталась.


Подскажите, пожалуйста.
Старый 27.02.2013, 15:31   #10  
user_ax is offline
user_ax
Участник
Аватар для user_ax
 
599 / 39 (3) +++
Регистрация: 07.10.2012
Адрес: ZP
Чудеса однако...В большом запросе если написать ledgerjournaltrans, в выпадающем списке НЕТ моего поля, Но, если написать просто

X++:
select PAYMPURPOSE_ZTR from LEDGERJOURNALTRANS
отрабатывает...мистика какая-то...


И снова видит это поле...либо кто-то вместе со мной работает с этой таблицей либо..либо не знаю...

Последний раз редактировалось user_ax; 27.02.2013 в 15:43.
Старый 27.02.2013, 16:01   #11  
user_ax is offline
user_ax
Участник
Аватар для user_ax
 
599 / 39 (3) +++
Регистрация: 07.10.2012
Адрес: ZP
Запрос заработал, но условие моё не отрабатывает...ищем дальше.
Старый 27.02.2013, 16:14   #12  
mazzy is offline
mazzy
Участник
Аватар для mazzy
Лучший по профессии 2015
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
Лучший по профессии 2011
Лучший по профессии 2009
 
29,472 / 4494 (208) ++++++++++
Регистрация: 29.11.2001
Адрес: Москва
Записей в блоге: 10
Цитата:
Сообщение от user_ax Посмотреть сообщение
Поставлена задача модифицировать запрос ... выводить поле ...

...
Буду благодарен за любые ответы.
Вот вам ответ:

Либо задача поставлена некорректно, либо вы поняли неправильно.
Запрос - ПОЛУЧАЕТ данные.
а в задаче сказано - ВЫВОДИТЬ данные.

другими словами, запрос никогда не выводит, выводит алгоритм построения отчета. А модифицировать вы должны почему-то запрос.
из-за внутренних противоречий в постановке в таком виде задачу не решить даже на листочке бумаги обычным карандашом.

Совет 1:
измените условие задачи.
скорее всего, вам нужно ВЫВОДИТЬ(!) ДРУГОЕ(!!!!) значение при определенных условиях.
поэтому:
1.1. не мучайте запрос, а запросом просто получайте оба поля во всех случаях
1.2. создайте display-метод, который выводит (отображает) то или иное поле в зависимости от условия

Совет 2:
даже в такой постановке задача не является правильной. Поведение "Вывод разных значений в зависимости от..." скорее всего запутает пользователя.

Получайте в запросе оба поля, выводите в отчет оба поля.
Скрывайте ВСЮ колонку в зависимости от условий перед выводом простейшим методом Conrtol.hide()
Старый 27.02.2013, 16:27   #13  
user_ax is offline
user_ax
Участник
Аватар для user_ax
 
599 / 39 (3) +++
Регистрация: 07.10.2012
Адрес: ZP
Цитата:
Сообщение от mazzy Посмотреть сообщение
Я с отчётами работаю впервые, поэтому, да, возможно, что я неверно понимаю, что нужно сделать. Мне консультант на словах сказала "Там есть условия, тебе нужно туда добавить одно и по сути всё". Но когда я увидел запрос, понял, что не всё...

Вот сама задача

Цитата:
Для отчета Свод дебиторской/кредиторской задолженности (Отчеты - Бухгалтерские отчеты), если задолженность сформирована через журнал накладных (Расчеты с поставщиками - Журналы - Накладные - Журнал накладных, LedgerJournalTable.JOURNALTYPE = 10)
предмет задолженности заполнять из поля Назначение платежа (LedgerJournalTrans.PaymPurpose_ZTR), а не из Предмета договора по конрагенту.
То есть, если journaltype = 10, нужно в отчёте печатать не LedgerJournalTrans.Txt, а LedgerJournalTrans.PaymPurpose_ZTR.

По поводу дисплей метода - спасибо, подумаю.

И вообще за столь подробные советы благодарю, полезно будет.

Дело в том, что запрос уже готов и куда именно в нём добавить нужное мне поле для выборки - пока затрудняюсь с этим.
Старый 27.02.2013, 16:39   #14  
mazzy is offline
mazzy
Участник
Аватар для mazzy
Лучший по профессии 2015
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
Лучший по профессии 2011
Лучший по профессии 2009
 
29,472 / 4494 (208) ++++++++++
Регистрация: 29.11.2001
Адрес: Москва
Записей в блоге: 10
Цитата:
Сообщение от user_ax Посмотреть сообщение
Вот сама задача



То есть, если journaltype = 10, нужно в отчёте печатать не LedgerJournalTrans.Txt, а LedgerJournalTrans.PaymPurpose_ZTR.
это типичный display-метод на таблице.
если говорить SQL-евским языком - дополнительное вычислимое поле в запросе.
просто в Аксапте вычислимое поле реализуется display-методом.

===================
Оффтопик:
PaymPurpose_ZTR - суффиксы. Хорошо то как, маладцы
Старый 27.02.2013, 16:45   #15  
user_ax is offline
user_ax
Участник
Аватар для user_ax
 
599 / 39 (3) +++
Регистрация: 07.10.2012
Адрес: ZP
Цитата:
Сообщение от mazzy Посмотреть сообщение
это типичный display-метод на таблице.
если говорить SQL-евским языком - дополнительное вычислимое поле в запросе.
просто в Аксапте вычислимое поле реализуется display-методом.

===================
Оффтопик:
PaymPurpose_ZTR - суффиксы. Хорошо то как, маладцы
Буду пробовать реализовать, благодарю.

Offtop:
Ну, не моя прихоть, политика компании такая ))
Старый 27.02.2013, 16:54   #16  
user_ax is offline
user_ax
Участник
Аватар для user_ax
 
599 / 39 (3) +++
Регистрация: 07.10.2012
Адрес: ZP
Логику вывода дописывать тогда нужно, ибо запрос строится на временных таблицах...и дисплей метод не подойдёт.
Есть другие пути решения?
Старый 27.02.2013, 17:52   #17  
user_ax is offline
user_ax
Участник
Аватар для user_ax
 
599 / 39 (3) +++
Регистрация: 07.10.2012
Адрес: ZP
Да, самое интересное, что даже в SQLManagmentStudio в выпадающем списке нужное мне поле есть, а комплилятор ругается, что не знает такого поля...
Как говорится "чудес не бывает", но другого объяснения нет у меня...
Старый 27.02.2013, 18:15   #18  
Poleax is offline
Poleax
Модератор
Аватар для Poleax
MCP
MCBMSS
Злыдни
 
1,353 / 595 (22) +++++++
Регистрация: 17.02.2005
Адрес: msk
Записей в блоге: 34
;)
Цитата:
Сообщение от user_ax Посмотреть сообщение
Запрос заработал, но условие моё не отрабатывает...ищем дальше.
Приведите текст кода запроса.

Вы случаем не пытаетесь в запросе у LedgerJournalTable найти поле PaymPurpose_ZTR?
Она явно в LedgerJournalTrans.PaymPurpose_ZTR
__________________

This posting is provided "AS IS" with no warranties, and confers no rights.
Старый 27.02.2013, 18:27   #19  
user_ax is offline
user_ax
Участник
Аватар для user_ax
 
599 / 39 (3) +++
Регистрация: 07.10.2012
Адрес: ZP
Цитата:
Сообщение от Poleax Посмотреть сообщение
Приведите текст кода запроса.

Вы случаем не пытаетесь в запросе у LedgerJournalTable найти поле PaymPurpose_ZTR?
Она явно в LedgerJournalTrans.PaymPurpose_ZTR
X++:
    if (object_id('tempdb..#vendsettlement') IS NOT NULL) begin drop table #vendsettlement; end
    if (object_id('tempdb..#custsettlement') IS NOT NULL) begin drop table #custsettlement; end
    if (object_id('tempdb..#saldo') IS NOT NULL) begin    drop table #saldo; end
    if (object_id('tempdb..#saldoPr') IS NOT NULL) begin    drop table #saldoPr; end
    select transrecid, sum(settleamountcur) as settlecur, sum(settleamountmst) as settlemst, sum(exchadjustment) as exchadj
        into #vendsettlement
        from vendsettlement (nolock) where transdate < '2013.01.01' and ltrim(accountnum) like '%19265155'
            and dataareaid = 'zkz'
        group by transrecid

    select transrecid, sum(settleamountcur) as settlecur, sum(settleamountmst) as settlemst, sum(exchadjustment) as exchadj
        into #custsettlement
        from custsettlement (nolock) where transdate < '2013.01.01' and ltrim(accountnum) like '%19265155'
            and dataareaid = 'zkz'
        group by transrecid

    select 'Поставщик' as k,
        ltrim(LedgerAccount_ZTR) as LedgerAccount_ZTR,
        --isNull(CodeId_ZTR, '') as Dimension,
        (select CompanyGroup from Dimensions (nolock) where Dimensions.Num = custtrans.Dimension  and Dimensions.dataareaid = 'zkz' ) as Dimension,
        custtrans.RContractCode,
        custtrans.accountnum, substring(custtable.name,1, 100) as name,
        substring('                                                                                                                                                      ',1,140) as n,
        isnull(country.name, '') as name1,
        case
          ---> 3780 26.02.2013
          --   when (Journaltype = 10)
          --   then substring(LedgerjournalTrans.PAYMPURPOSE_ZTR,1,1000)
        --<-
            when SubjectOfAgreement_ZTR != '' then SubjectOfAgreement_ZTR
            when (LedgerjournalTrans.BankCentralBankPurposeText is not null and LedgerjournalTrans.BankCentralBankPurposeText != '' and  Journaltype = 4)
               then LedgerjournalTrans.BankCentralBankPurposeText
               when (LedgerjournalTrans.Txt is not null and LedgerjournalTrans.Txt != '' and (Journaltype = 0 or Journaltype = 45))
                then custtrans.Txt
            when (substring(rContractTable.RContractSubject,1,1000) is not null and substring(rContractTable.RContractSubject,1,1000) != '')  then substring(rContractTable.RContractSubject,1,1000)
            else ''
        end as RContractSubject,
        
        isnull(rContractTable.RCONTRACTNUMBER, '') as RCONTRACTNUMBER,
        sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0)) as mst,
        CustTrans.transdate,
        custtrans.DueDate,
      case
            when dateDiff(month, CustTrans.Duedate, '2013.01.01') = 0 and day('2013.01.01') > day(CustTrans.Duedate)
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            when dateDiff(month, CustTrans.Duedate, '2013.01.01') = 1 and day('2013.01.01') <= day(CustTrans.Duedate)
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            else 0
        end as 'p1',
      case
            when dateDiff(month, CustTrans.Duedate,'2013.01.01') = 1 and day('2013.01.01') > day(CustTrans.Duedate)
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            when ((dateDiff(month, CustTrans.Duedate,'2013.01.01') > 1) and (dateDiff(month, CustTrans.Duedate,'2013.01.01') < 3))
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            when dateDiff(month, CustTrans.Duedate,'2013.01.01') = 3 and day('2013.01.01') <= day(CustTrans.Duedate)
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            else 0
        end as 'p2',
        case
            when dateDiff(month, CustTrans.Duedate,'2013.01.01') = 3 and day('2013.01.01') > day(CustTrans.Duedate)
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            when ((dateDiff(month, CustTrans.Duedate,'2013.01.01') > 3) and (dateDiff(month, CustTrans.Duedate,'2013.01.01') < 36))
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            when dateDiff(month, CustTrans.Duedate,'2013.01.01') = 36 and day('2013.01.01') <= day(CustTrans.Duedate)
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            else 0
        end as 'p3',
        case
            when dateDiff(month, CustTrans.Duedate,'2013.01.01') = 36 and day('2013.01.01') > day(CustTrans.Duedate)
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            when ((dateDiff(month, CustTrans.Duedate,'2013.01.01') > 36))
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            else 0
        end as 'p4',
        sum(-amountcur)-sum(-isnull(settlecur,0)) as cur,
        custtrans.currencycode, ' ' as f,

        isnull(rContractTable.RContractAccount, '') as RContractAccount,
        isnull(RContractPartnerType,'') as RContractPartnerType,
        case
            when (LedgerjournalTrans.PaymentStatusUserId_ZTR != '')
                then LedgerjournalTrans.PaymentStatusUserId_ZTR
            when  custtrans.CreatedBy != '' then custtrans.CreatedBy
            else ''
        end as CreatedBy , custtrans.Dimension3_, custtrans.Dimension7_
        into #saldo
        from vendtrans custtrans (nolock)
        left join #vendsettlement (nolock) on custtrans.recid = #vendsettlement.transrecid
        inner join vendtable custtable (nolock) on custtable.accountnum = custtrans.accountnum and custtable.dataareaid = 'zkz'left join AddressCountryRegion country (nolock) on country.CountryRegionId = custtable.CountryRegionId and country.dataareaid = 'zkz'left join rContractTable (Nolock) on rContractTable.RContractPartnerType = '1' and
                      rContractTable.RContractCode        = custtrans.RContractCode        and
                      rContractTable.RContractAccount     = custtrans.RContractAccount --and RContractStatus = '1'
                      and rContractTable.dataareaid = 'zkz'
        left join (select voucher, POSTINGPROFILE, offsetpostingprofile_ru, PaymentStatusUserId_ZTR,
                    LedgerjournalTrans.BankCentralBankPurposeText,LedgerjournalTrans.txt, Journaltype
        from LedgerjournalTrans (nolock)
         inner join LedgerjournalTable on LedgerjournalTrans.journalnum = LedgerjournalTable.journalnum and posted = 1
            and Journaltype in(0, 4,  45)  and LedgerjournalTrans.dataareaid = 'zkz'
            and LedgerjournalTrans.dataareaid = 'zkz'
            ) as LedgerjournalTrans
            on custtrans.voucher = LedgerjournalTrans.voucher
            and (LedgerjournalTrans.postingprofile in
            (select vendledgeraccounts.postingprofile from vendledgeraccounts (nolock)
            where (accountCode = 2 or (accountcode = 1 and num = vendgroup))
                and vendledgeraccounts.dataareaid = 'zkz' and
            ltrim(sumaccount) = ltrim(LedgerAccount_ZTR)) or (offsetpostingprofile_ru in
            (select vendledgeraccounts.postingprofile from vendledgeraccounts (nolock)
            where (accountCode = 2 or (accountcode = 1 and num = vendgroup))
                and vendledgeraccounts.dataareaid = 'zkz' and
            ltrim(sumaccount) = ltrim(LedgerAccount_ZTR))))
        --left join RContractTypes (nolock) on RContractTypes.ContractCode = custtrans.RContractCode and RContractTypes.ContractPartnerType = 1
        where CustTrans.transdate < '2013.01.01' and (closed = '19000101' or closed >= '2013.01.01')
            and ltrim(LedgerAccount_ZTR) in ('6312100')
            and ltrim(custtrans.accountnum) like '%19265155' and custtrans.dataareaid = 'zkz'
            and LedgerAccount_ZTR not in(select accountnum from NotIncludeAccount_ZTR (nolock) where NotIncludeAccount_ZTR.dataareaid = 'zkz')

        group by LedgerAccount_ZTR, custtrans.RContractCode,
            custtrans.accountnum, custtable.name,
            country.name,
            substring(rContractTable.RContractSubject,1,1000),
            rContractTable.RCONTRACTNUMBER,
            CustTrans.transdate,
            custtrans.DueDate,custtrans.Dimension,
            custtrans.currencycode,rContractTable.RContractAccount,RContractPartnerType
            ,PaymentStatusUserId_ZTR, LedgerjournalTrans.BankCentralBankPurposeText ,custtrans.CreatedBy, --CodeId_ZTR,
            LedgerjournalTrans.txt, Journaltype, SubjectOfAgreement_ZTR ,custtrans.Txt,
            --Ledgerjournaltrans.PAYMPURPOSE_ZTR,
        --having sum(amountcur) != 0 or sum(amountmst) != 0
  custtrans.Dimension3_, custtrans.Dimension7_
    insert into #saldo
    select 'Клиент' as k ,/*' ' as g,*/ ltrim(LedgerAccount_ZTR) as LedgerAccount_ZTR,
        isNull(CodeId_ZTR, '') as Dimension,
        --(select CompanyGroup from Dimensions (nolock) where Dimensions.Num = custtrans.Dimension) as Dimension,
        custtrans.RContractCode,
        custtrans.accountnum, substring(custtable.name,1, 100),
        (select FinalDelvCustName_ZTR from SalesTable where SalesTable.SalesId = custtrans.DocId_ZTR) as n,
        isnull(country.name, '') as name1,
        case
         ---> 3780 26.02.2013
         when (Journaltype = 10)
         then substring(LedgerjournalTrans.PAYMPURPOSE_ZTR,1,500)
        
          --<-
            when SubjectOfAgreement_ZTR != '' then SubjectOfAgreement_ZTR
            /*when (LedgerjournalTrans.BankCentralBankPurposeText is not null and LedgerjournalTrans.BankCentralBankPurposeText != '' and  Journaltype = 7)
                then LedgerjournalTrans.BankCentralBankPurposeText*/
            when (LedgerjournalTrans.Txt is not null and LedgerjournalTrans.Txt != '' /*and (Journaltype = 0 or Journaltype = 45)*/)
                then custtrans.Txt
            when (substring(rContractTable.RContractSubject,1,1000) is not null and substring(rContractTable.RContractSubject,1,1000) != '')  then substring(rContractTable.RContractSubject,1,1000)

            else ''
        end as RContractSubject,
        isnull(rContractTable.RCONTRACTNUMBER, '') as RCONTRACTNUMBER,
        sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0)) as mst,
        Custtrans.transdate,
        custtrans.DueDate,
      case
            when dateDiff(month, CustTrans.Duedate, '2013.01.01') = 0 and day('2013.01.01') > day(CustTrans.Duedate)
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            when dateDiff(month, CustTrans.Duedate, '2013.01.01') = 1 and day('2013.01.01') <= day(CustTrans.Duedate)
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            else 0
        end as 'p1',
      case
            when dateDiff(month, CustTrans.Duedate,'2013.01.01') = 1 and day('2013.01.01') > day(CustTrans.Duedate)
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            when ((dateDiff(month, CustTrans.Duedate,'2013.01.01') > 1) and (dateDiff(month, CustTrans.Duedate,'2013.01.01') < 3))
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            when dateDiff(month, CustTrans.Duedate,'2013.01.01') = 3 and day('2013.01.01') <= day(CustTrans.Duedate)
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            else 0
        end as 'p2',
        case
            when dateDiff(month, CustTrans.Duedate,'2013.01.01') = 3 and day('2013.01.01') > day(CustTrans.Duedate)
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            when ((dateDiff(month, CustTrans.Duedate,'2013.01.01') > 3) and (dateDiff(month, CustTrans.Duedate,'2013.01.01') < 36))
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            when dateDiff(month, CustTrans.Duedate,'2013.01.01') = 36 and day('2013.01.01') <= day(CustTrans.Duedate)
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            else 0
        end as 'p3',
        case
            when dateDiff(month, CustTrans.Duedate,'2013.01.01') = 36 and day('2013.01.01') > day(CustTrans.Duedate)
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            when ((dateDiff(month, CustTrans.Duedate,'2013.01.01') > 36))
            then sum(-amountmst)-sum(-isnull(settlemst,0))+sum(-isnull(exchadj,0))
            else 0
        end as 'p4',

        sum(-amountcur)-sum(-isnull(settlecur,0)) as cur,
        custtrans.currencycode, '' as f,
        isnull(rContractTable.RContractAccount,'') as RContractAccount,
        isnull(RContractPartnerType,'') as RContractPartnerType,
        case
            when (LedgerjournalTrans.PaymentStatusUserId_ZTR != '')  then LedgerjournalTrans.PaymentStatusUserId_ZTR
            when  custtrans.CreatedBy != '' then custtrans.CreatedBy
            else ''
        end as CreatedBy
 , custtrans.Dimension3_, custtrans.Dimension7_
        from custtrans  (nolock)
        left join #custsettlement on custtrans.recid = #custsettlement.transrecid
        inner join custtable (nolock) on custtable.accountnum = custtrans.accountnum and custtable.dataareaid = 'zkz'left join AddressCountryRegion country (nolock) on country.CountryRegionId = custtable.CountryRegionId and country.dataareaid = 'zkz'left join rContractTable (Nolock) on rContractTable.RContractPartnerType = '0' and
                      rContractTable.RContractCode        = custtrans.RContractCode        and
                      rContractTable.RContractAccount     = custtrans.RContractAccount --and RContractStatus = '1'
                      and rContractTable.dataareaid = 'zkz'
        left join LedgerjournalTrans (nolock) on custtrans.voucher = LedgerjournalTrans.voucher
            and LedgerjournalTrans.dataareaid = 'zkz'
            and (LedgerjournalTrans.postingprofile in
            (select custledgeraccounts.postingprofile from custledgeraccounts (nolock)
            where (accountCode = 2 or (accountcode = 1 and num = custgroup))
            and custledgeraccounts.dataareaid = 'zkz' and
            ltrim(sumaccount) = ltrim(LedgerAccount_ZTR)) or (offsetpostingprofile_ru in
            (select custledgeraccounts.postingprofile from custledgeraccounts (nolock)
            where (accountCode = 2 or (accountcode = 1 and num = custgroup))
            and custledgeraccounts.dataareaid = 'zkz'  and
            ltrim(sumaccount) = ltrim(LedgerAccount_ZTR))))
        left join LedgerjournalTable on LedgerjournalTrans.journalnum = LedgerjournalTable.journalnum and posted = 1
            and Journaltype in(0, 7, 45) and LedgerjournalTable.dataareaid = 'zkz'
        left join RContractTypes (nolock) on RContractTypes.ContractCode = custtrans.RContractCode and RContractTypes.ContractPartnerType = 0
            and RContractTypes.dataareaid = 'zkz'
        where Custtrans.transdate < '2013.01.01' and (closed = '19000101' or closed >= '2013.01.01')
                    and ltrim(LedgerAccount_ZTR) in ('6312100')
                    and ltrim(custtrans.accountnum) like '%19265155'
                    and LedgerAccount_ZTR not in(select accountnum from NotIncludeAccount_ZTR (nolock) where NotIncludeAccount_ZTR.dataareaid = 'zkz')
                    and custtrans.dataareaid = 'zkz'

        group by custtrans.accountnum, custtrans.currencycode, custtrans.RContractCode, custtrans.Dimension,
            rContractTable.RContractCode,
            substring(rContractTable.RContractSubject,1,1000),
            LedgerAccount_ZTR, Custtrans.transdate,RContractPartnerType, rContractTable.RCONTRACTNUMBER,
            custtrans.DueDate,
            custtable.name, country.name,rContractTable.RContractAccount,RContractPartnerType,
            PaymentStatusUserId_ZTR, LedgerjournalTrans.BankCentralBankPurposeText, custtrans.CreatedBy, CodeId_ZTR,
            LedgerjournalTrans.txt, SubjectOfAgreement_ZTR, custtrans.Txt, custtrans.DocId_ZTR,
             substring(Ledgerjournaltrans.PAYMPURPOSE_ZTR,1,500),
            Ledgerjournaltable.JOURNALTYPE,
           
             --, Journaltype
        --having sum(amountcur) != 0 or sum(amountmst) != 0
  custtrans.Dimension3_, custtrans.Dimension7_
    select k,
        case when (mst < 0 or cur < 0) then 'Д' else 'К' end as pr,
        case when (mst < 0 or cur < 0) then BalSheetDt_ZTR
            when (mst > 0 or cur > 0) then BalSheetKr_ZTR
        end as bal,
        ltrim(LedgerAccount_ZTR) as LedgerAccount_ZTR,
        #saldo.Dimension,
        #saldo.accountnum,
        #saldo.name,
        n,
        name1,
        #saldo.RContractSubject,
        #saldo.RCONTRACTNUMBER,
        case when (mst < 0) then -mst else mst end as mst,
        transdate,
        #saldo.DueDate,
        case when (p1 < 0) then -p1 else p1 end as p1,
        case when (p2 < 0) then -p2 else p2 end as p2,
        case when (p3 < 0) then -p3 else p3 end as p3,
        case when (p4 < 0) then -p4 else p4 end as p4,
        case when (cur < 0) then -cur else cur end as cur,
        #saldo.currencycode,
        #saldo.CreatedBy
 , #saldo.Dimension3_, #saldo.Dimension7_
    into #saldoPr
    from #saldo
    inner join LedgerTable (nolock) on ltrim(LedgerTable.accountNum) = ltrim(LedgerAccount_ZTR) and LedgerTable.dataareaid = 'zkz'
    left join rContractTable (Nolock) on rContractTable.RContractPartnerType = #saldo.RContractPartnerType and
                      rContractTable.RContractCode        = #saldo.RContractCode        and
                      rContractTable.RContractAccount     = #saldo.RContractAccount --and RContractStatus = '1'
                      and rContractTable.dataareaid = 'zkz'
    where #saldo.CreatedBy like '%'
    order by #saldo.accountnum,#saldo.currencycode,ltrim(LedgerAccount_ZTR),transdate
o
Я добавил свой код в условие case в 3 селекте и последнем (комментарии --->3780 26.02.2013)
Но в первом случае он ругается, что не знает такого поля, хотя выбираю его из выпадающего списка, я так понимаю, что если решить проблему с первым case-ом, тогда будет отображаться то, что нужно.

Последний раз редактировалось user_ax; 27.02.2013 в 18:29.
Старый 27.02.2013, 18:44   #20  
Wamr is offline
Wamr
----------------
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
 
1,737 / 858 (32) +++++++
Регистрация: 15.01.2002
Адрес: Москва
Записей в блоге: 7
для полноты картины нужен текст ошибки, который выдает SQL
Теги
sql, выборка, запрос (query)

 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
Перебор N критериев в SQL запросе berlioz DAX: Программирование 6 22.08.2007 11:33
Влияние WHERE в запросе (SQL) Как объяснить? lagr221374 DAX: Программирование 4 24.08.2006 16:03
Вопрос по SQL и по Аксапте? Hidden DAX: Прочие вопросы 4 30.11.2005 21:18
SQL в Аксапте Smith DAX: Программирование 7 04.03.2005 11:13
Можно ли в аксапте реализовать такой SQL запрос: Sergey_1972 DAX: Программирование 14 18.03.2004 16:33

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 08:33.
Powered by vBulletin® v3.8.5. Перевод: zCarot
Контактная информация, Реклама.