Как использовать оператор case несколько раз в одном столбце на сервере sql - PullRequest
0 голосов
/ 02 марта 2020

Я бы хотел, чтобы сумма отображалась, если ноль не был показан, этот запрос получен для меня только отдельно

Как мне добавить этот запрос к моему запросу

case when [Summa]=0 then null else round(a.Summa,2) end as Summa

Это запрос, который мне нужен

SELECT
    [a].[id],
    CONVERT(NVARCHAR(10), [a].[Date], 104) AS [Data],
    [j].[Login],
    [b].[Name] AS [NameAgency],
    [c].[Name] AS [NamePosition],
    [d].[Name] AS [NameOperatonsType],
    [e].[Name] AS [NamePartnerType],
    [f].[Name] AS [NameType],
    [g].[Name] AS [NamePartners],
    [h].[name] AS [NameBank],
    [i].[name] AS [NameCurrency],
    CASE       
        WHEN [d].[ID] = 2 THEN
            '0'
        ELSE
            [a].[Summa]
    END AS [Prikhod],
    CASE
        WHEN [d].[ID] = 1 THEN
            '0'
        ELSE
            [a].[Summa]
    END AS [Raskhod],
    [a].[Comment]
FROM
    [Operations] AS [a] LEFT JOIN
    [Agency] AS [b] ON [a].[AgencyID] = [b].[ID] LEFT JOIN
    [Position] AS [c] ON [a].[PositionID] = [c].[ID] LEFT JOIN
    [OperatonsType] AS [d] ON [a].[OperType] = [d].[ID] LEFT JOIN
    [PartnerType] AS [e] ON [a].[ParentID] = [e].[ID] LEFT JOIN
    [NameType] AS [f] ON [a].[NameTypeID] = [f].[ID] LEFT JOIN
    [Partners] AS [g] ON [a].[PartnerID] = [g].[id] LEFT JOIN
    [Bank] AS [h] ON [a].[BankID] = [h].[id] LEFT JOIN
    [Currency] AS [i] ON [a].[CurrencyID] = [i].[id] LEFT JOIN
    [Users] AS [j] ON [a].[UserID] = [j].[ID]
WHERE
    [a].[Date] = CAST(GETDATE() AS DATE)
ORDER BY
    [a].[id] DESC;

enter image description here

Я хочу заменить 0 на NULL для столбцов Приход и Расход. Пожалуйста, дайте мне знать, какие изменения необходимо сделать.

Ответы [ 2 ]

1 голос
/ 02 марта 2020

Для этого есть встроенная функция: NULLIF () . Эта функция возвращает NULL, когда первый аргумент совпадает со вторым.

В вашем случае вы говорите: Вернуть NULL, если мой CASE оценивается как 0.

Попробуйте:

SELECT NULLIF(
        CASE WHEN [d].[ID] = 2 THEN '0'
        ELSE [a].[Summa] END, '0') AS [Prikhod],
       NULLIF(
        CASE WHEN [d].[ID] = 1 THEN '0'
        ELSE [a].[Summa] END, '0') AS [Raskhod]
FROM...

Подсказка: в зависимости от типа данных a.Summa может быть неправильным указывать нулевые значения в виде строки ('0'). Мы надеемся, что неявное преобразование вернет ожидаемое вами значение, но лучше придерживаться одного типа данных явно.

1 голос
/ 02 марта 2020

Попробуйте это:

select *,case when Prikhod = 0 then NULL ELSE Prikhod END ,case when Raskhod = 0 then NULL ELSE Raskhod END   from (
SELECT
    [a].[id],
    CONVERT(NVARCHAR(10), [a].[Date], 104) AS [Data],
    [j].[Login],
    [b].[Name] AS [NameAgency],
    [c].[Name] AS [NamePosition],
    [d].[Name] AS [NameOperatonsType],
    [e].[Name] AS [NamePartnerType],
    [f].[Name] AS [NameType],
    [g].[Name] AS [NamePartners],
    [h].[name] AS [NameBank],
    [i].[name] AS [NameCurrency],
    CASE       
        WHEN [d].[ID] = 2 THEN
            '0'
        ELSE
            [a].[Summa]
    END AS [Prikhod],
    CASE
        WHEN [d].[ID] = 1 THEN
            '0'
        ELSE
            [a].[Summa]
    END AS [Raskhod],
    [a].[Comment]
FROM
    [Operations] AS [a] LEFT JOIN
    [Agency] AS [b] ON [a].[AgencyID] = [b].[ID] LEFT JOIN
    [Position] AS [c] ON [a].[PositionID] = [c].[ID] LEFT JOIN
    [OperatonsType] AS [d] ON [a].[OperType] = [d].[ID] LEFT JOIN
    [PartnerType] AS [e] ON [a].[ParentID] = [e].[ID] LEFT JOIN
    [NameType] AS [f] ON [a].[NameTypeID] = [f].[ID] LEFT JOIN
    [Partners] AS [g] ON [a].[PartnerID] = [g].[id] LEFT JOIN
    [Bank] AS [h] ON [a].[BankID] = [h].[id] LEFT JOIN
    [Currency] AS [i] ON [a].[CurrencyID] = [i].[id] LEFT JOIN
    [Users] AS [j] ON [a].[UserID] = [j].[ID]
WHERE
    [a].[Date] = CAST(GETDATE() AS DATE)
    ) t
ORDER BY
    t.[id] DESC;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...