AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / dba / Perguntas / 127688
Accepted
Kaishu
Kaishu
Asked: 2016-01-29 23:28:58 +0800 CST2016-01-29 23:28:58 +0800 CST 2016-01-29 23:28:58 +0800 CST

Como usar a operação SET na cláusula CASE no SQL?

  • 772

Tenho a seguinte estrutura, e estou fazendo uma SEToperação em uma CASEcláusula mas está gerando um erro:

Sintaxe incorreta próximaSET

Consulta:

DECLARE @tbl_Result TABLE
(
    RowID INT IDENTITY(1,1),
    TtlNOfCmpSale7to12 INT,
    TtlNOfCmpSale4to6 INT,
    TtlNOfCmpSale0to3 INT,
    TtlNOfCmpSaleSpanFirst SMALLINT DEFAULT 0,
    TtlNOfCmpSaleSpanSecond SMALLINT DEFAULT 0,
    TtlNOfCmpSaleSpanThird SMALLINT DEFAULT 0
);

DECLARE 
    @Declining FLOAT,
    @StableStart SMALLINT,
    @StableEnd SMALLINT,
    @Increasing SMALLINT;

SELECT
    @Declining = 0.90,
    @StableStart = 90,
    @StableEnd = 110,
    @Increasing = 110;

DECLARE @TrendValue FLOAT; 

UPDATE R
SET R.TtlNOfCmpSaleSpanFirst =
    CASE
        WHEN R.TtlNOfCmpSale7to12 != 0 THEN
            SET @TrendValue = R.TtlNOfCmpSale4to6*2/R.TtlNOfCmpSale7to12
            (
                CASE 
                    WHEN @TrendValue > @Increasing THEN 0
                    WHEN @TrendValue >  @StableStart 
                        AND @TrendValue <  @StableEND THEN 1
                    WHEN @TrendValue < @Declining THEN 2
                END
            )
    END,
    R.TtlNOfCmpSaleSpanSecond = 
        CASE 
            WHEN R.TtlNOfCmpSale4to6!= 0 THEN
                SET @TrendValue = R.TtlNOfCmpSale0to3/R.TtlNOfCmpSale4to6
                (
                    CASE 
                        WHEN @TrendValue > @Increasing THEN 0
                        WHEN @TrendValue >  @StableStart 
                            AND @TrendValue <  @StableEND THEN 1
                        WHEN @TrendValue < @Declining THEN 2
                    END
                )
        END,
    R.TtlNOfCmpSaleSpanThird = 
        CASE 
            WHEN R.TtlNOfCmpSale7to12 != 0 THEN
                SET @TrendValue = R.TtlNOfCmpSale0to3/R.TtlNOfCmpSale7to12
                (
                    CASE 
                        WHEN @TrendValue > @Increasing THEN 0
                        WHEN @TrendValue >  @StableStart 
                            AND @TrendValue <  @StableEND THEN 1
                        WHEN @TrendValue < @Declining THEN 2
                    END
                )
        END
FROM Result R;

Seria melhor se houvesse outra maneira de armazenar o resultado da expressão em @TrendValue para que não houvesse necessidade de calcular essa expressão todas as vezes.

Também seria bom evitar erros de divisão por zero (é por isso que adicionei as várias R.TtlNOfCmpSale7to12 != 0verificações).

sql-server sql-server-2012
  • 2 2 respostas
  • 10165 Views

2 respostas

  • Voted
  1. Best Answer
    Mark Sinkinson
    2016-01-30T00:25:35+08:002016-01-30T00:25:35+08:00

    Com base no seu comentário, você parece estar procurando uma maneira de evitar repetir o mesmo cálculo indefinidamente.

    Você pode usar APPLY VALUESpara calcular os valores necessários uma vez e, em seguida, usar a coluna com alias no restante de seus cálculos.

    DECLARE @Declining FLOAT,
    @StableStart SMALLINT,
    @StableEnd SMALLINT,
    @Increasing SMALLINT
    
    SELECT  @Declining = 0.90,
    @StableStart = 90,
    @StableEnd = 110,
    @Increasing = 110
    
    DECLARE @TrendValue FLOAT; 
    
    UPDATE R
    SET
     R.TtlNOfCmpSaleSpanFirst = 
                CASE 
                    WHEN R.TtlNOfCmpSale7to12 != 0 THEN
                      CASE WHEN Trends.TrendFirst > @Increasing THEN 0
                            WHEN Trends.TrendFirst >  @StableStart AND Trends.TrendFirst <  @StableEND THEN 1
                            WHEN Trends.TrendFirst < @Declining THEN 2
                      END
                END,
     R.TtlNOfCmpSaleSpanSecond = 
                CASE 
                    WHEN R.TtlNOfCmpSale4to6!= 0 THEN
                      CASE WHEN Trends.TrendSecond > @Increasing THEN 0
                            WHEN Trends.TrendSecond >  @StableStart AND Trends.TrendSecond <  @StableEND THEN 1
                            WHEN Trends.TrendSecond < @Declining THEN 2
                      END
                END,
    
     R.TtlNOfCmpSaleSpanThird = 
                CASE 
                    WHEN R.TtlNOfCmpSale7to12 != 0 THEN
                      CASE WHEN Trends.TrendThird > @Increasing THEN 0
                            WHEN Trends.TrendThird >  @StableStart AND Trends.TrendThird <  @StableEND THEN 1
                            WHEN Trends.TrendThird < @Declining THEN 2
                      END
                END
    
    FROM Result R
    CROSS APPLY (
        VALUES (IIF(R.TtlNOfCmpSale7to12 <> 0, R.TtlNOfCmpSale4to6*2/R.TtlNOfCmpSale7to12, 0)
                  IIF(R.TtlNOfCmpSale4to6 <> 0, R.TtlNOfCmpSale0to3/R.TtlNOfCmpSale4to6, 0) 
                  IIF(R.TtlNOfCmpSale7to12 <> 0, R.TtlNOfCmpSale0to3/R.TtlNOfCmpSale7to12, 0)
    ) AS Trends(TrendFirst, TrendSecond, TrendThird);
    
    • 4
  2. Julien Vavasseur
    2016-01-30T00:40:53+08:002016-01-30T00:40:53+08:00

    Isso deve funcionar:

    WITH data AS(
        SELECT TtlNOfCmpSaleSpanFirst, TtlNOfCmpSaleSpanSecond, TtlNOfCmpSaleSpanThird
            , TtlNOfCmpSale0to3, TtlNOfCmpSale4to6, TtlNOfCmpSale7to12
            , TrendValueFirst = IIF(R.TtlNOfCmpSale7to12 = 0, 0, R.TtlNOfCmpSale4to6*2/R.TtlNOfCmpSale7to12)
            , TrendValueSecond = IIF(R.TtlNOfCmpSale4to6 = 0, 0, R.TtlNOfCmpSale0to3/R.TtlNOfCmpSale4to6)
            , TrendValueThird = IIF(R.TtlNOfCmpSale7to12 = 0, 0, R.TtlNOfCmpSale0to3/R.TtlNOfCmpSale7to12)
        FROM @tbl_Resul R
    )
    -- SELECT
    UPDATE R SET 
        TtlNOfCmpSaleSpanFirst = CASE 
                WHEN TrendValueFirst > @Increasing THEN 0
                WHEN TrendValueFirst >  @StableStart AND TrendValueFirst <  @StableEND THEN 1
                WHEN TrendValueFirst < @Declining THEN 2
            END
        , TtlNOfCmpSaleSpanSecond = CASE 
                WHEN TrendValueSecond > @Increasing THEN 0
                WHEN TrendValueSecond >  @StableStart AND TrendValueSecond <  @StableEND THEN 1
                WHEN TrendValueSecond < @Declining THEN 2
            END
        , TtlNOfCmpSaleSpanThird = CASE 
                WHEN TrendValueThird > @Increasing THEN 0
                WHEN TrendValueThird >  @StableStart AND TrendValueThird <  @StableEND THEN 1
                WHEN TrendValueThird < @Declining THEN 2
            END
    FROM data R;
    

    Ele usa IIF para definir TrendValue como 0 quando o divisor é igual a 0.

    O CTE obtém todas as linhas da sua tabela e calcula os 3 valores de tendência. Você pode então SELECIONAR ou ATUALIZAR as colunas da tabela principal usada no CTE. Isso funciona como um UPDATE em uma VIEW.

    Dados de amostra e saída são fornecidos abaixo.

    Amostra:

    DECLARE @tbl_Resul TABLE(
        RowID INT IDENTITY(1,1),
        TtlNOfCmpSale7to12 INT,
        TtlNOfCmpSale4to6 INT,
        TtlNOfCmpSale0to3 INT,
        TtlNOfCmpSaleSpanFirst SMALLINT DEFAULT 0,
        TtlNOfCmpSaleSpanSecond SMALLINT DEFAULT 0,
        TtlNOfCmpSaleSpanThird SMALLINT DEFAULT 0
    );
    
    INSERT INTO @tbl_Resul(TtlNOfCmpSaleSpanFirst, TtlNOfCmpSaleSpanSecond, TtlNOfCmpSaleSpanThird, TtlNOfCmpSale0to3, TtlNOfCmpSale4to6, TtlNOfCmpSale7to12) VALUES
        (null, null, null, 9505, 85, 415)
        , (null, null, null, 850, 700, 15)
        , (null, null, null, 650, 20, 4)
        , (null, null, null, 650, 20, 0);
    
    DECLARE @Declining FLOAT = 0.90;
    DECLARE @StableStart SMALLINT = 90;
    DECLARE @StableEnd SMALLINT = 110;
    DECLARE @Increasing SMALLINT = 110;
    

    Resultado:

    RowID   TtlNOfCmpSale7to12  TtlNOfCmpSale4to6   TtlNOfCmpSale0to3   TtlNOfCmpSaleSpanFirst  TtlNOfCmpSaleSpanSecond TtlNOfCmpSaleSpanThird
    1       415                 85                  9505                2                       0                       NULL
    2       15                  700                 850                 1                       NULL                    NULL
    3       4                   20                  650                 NULL                    NULL                    0
    4       0                   20                  650                 NULL                    NULL                    NULL
    
    • 3

relate perguntas

  • SQL Server - Como as páginas de dados são armazenadas ao usar um índice clusterizado

  • Preciso de índices separados para cada tipo de consulta ou um índice de várias colunas funcionará?

  • Quando devo usar uma restrição exclusiva em vez de um índice exclusivo?

  • Quais são as principais causas de deadlocks e podem ser evitadas?

  • Como determinar se um Índice é necessário ou necessário

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve