IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Développement SQL Server Discussion :

Requete Select MAX et Select TOP 1 DESC


Sujet :

Développement SQL Server

  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    816
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 816
    Points : 49
    Points
    49
    Par défaut Requete Select MAX et Select TOP 1 DESC
    Bonjour à tous,


    SQL 2008 r2

    Je dispose d'une requête SQL de notre outil métier. Dans cette requête j'ai une partie de la requête qui fait appel à une sous requête (j’espère que c'est le bon terme) ci-dessous

    La sous requete de base
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    (SELECT MAX (taHistorico.FechaHoraCreacion) FROM taHistorico 
    WHERE taHistorico.Emp = '001' AND 
    taHistorico.Almacen = '11' AND 
    taHistorico.NumIntArticulo = taArticuloAlma.NumInterno AND
    taHistorico.FechaHoraCreacion <= year ('31-07-2013 23:59:59.000') * 10000000000 + month('31-07-2013 23:59:59.000') * 100000000 + day ('31-07-2013 23:59:59.000') * 1000000 + 235959)
    La même partie que j'ai modifié:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    (SELECT TOP 1 taHistorico.FechaHoraCreacion 
    FROM taHistorico 
    WHERE taHistorico.Emp = '001' AND 
    taHistorico.Almacen = '11' AND 
    taHistorico.NumIntArticulo = taArticuloAlma.NumInterno AND
    taHistorico.FechaHoraCreacion <= year ('31-07-2013 23:59:59.000') * 10000000000 + month('31-07-2013 23:59:59.000') * 100000000 + day ('31-07-2013 23:59:59.000') * 1000000 + 235959
    ORDER BY taHistorico.FechaHoraCreacion DESC)
    Avec ces deux requête je devrait arriver au même résultat ?

    Car si je comprend la première requête, je demande la valeur Maximum de taHistorico.FechaHoraCreacion et dans la requête modifiée je demande bien la même chose je veux uniquement la premier valeur en rangeant par ordre du plus grand au plus petit.

    Est-ce commis une erreur ?

    guigui69

  2. #2
    Membre du Club
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Janvier 2007
    Messages
    36
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : Industrie

    Informations forums :
    Inscription : Janvier 2007
    Messages : 36
    Points : 63
    Points
    63
    Par défaut
    Bonjour,

    Ces requêtes devraient donner le même résultat. Ce n'est pas le cas ?

    Cordialement

  3. #3
    Modérateur

    Profil pro
    dba
    Inscrit en
    Janvier 2010
    Messages
    5 643
    Détails du profil
    Informations personnelles :
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : dba

    Informations forums :
    Inscription : Janvier 2010
    Messages : 5 643
    Points : 13 092
    Points
    13 092
    Par défaut
    Il existe une petite différence sournoise : lorsque aucune ligne ne correspond aux critères du filtre, la requête avec MAX renverra une ligne (contenant NULL), alors que la requête avec TOP(1) ne renverra aucune ligne.

    Cette petite différence peut engendrer des comportements totalement différents quand la requête est utilisée en sous requête.

    Par exemple, utilisée avec un NOT IN :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    SELECT a,b,c
    FROM UneTable
    WHERE c NOT IN (
        SELECT MAX(x)
        FROM UneAutreTable
        WHERE 1 = 2
    )
    Ne renverra aucune ligne

    Alors que
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
    SELECT a,b,c
    FROM UneTable
    WHERE c NOT IN (
        SELECT top 1 x
        FROM UneAutreTable
        WHERE 1 = 2
         ORDER BY x DESC
    )
    Renverra toutes les lignes de UneTable

    (Ces deux requêtes sont stupides sur le principe, mais c'est pour l'exemple )


    Conclusion : postez votre requête complète, et indiquez ce qui vous semble anormal (si vous postez, j'imagine qu'il y a quelque chose qui ne va pas, mais vous n'avez pas indiqué quoi ! )

  4. #4
    Membre du Club
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    816
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 816
    Points : 49
    Points
    49
    Par défaut
    Voici la requete:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
     
    SELECT tgMarca.Descrip,
    taArticuloAlma.Emp,
    tgEmpresa.Razon,
    tgAlma.Descrip,
    tgGrupoCont.Descrip,
    taFamInterna.Descrip,
    taFamProveedor.Descrip, taArticulo.ReferenciaEditada,
    taArticulo.ReferenciaOrden,
    taArticulo.Descrip,
    taArticulo.CodigoRim,
    taArticuloAlma.Almacen,
    taArticuloAlma.NumInterno,
    taArticuloAlma.FechaAlta,
    taArticuloAlma.FechaUltEntrada,
    taArticuloAlma.FechaUltSalida,
    taArticuloAlma.FechaUltInven,
    taArticuloAlma.Ubicacion1,
    taArticuloAlma.Baja,
    taArticuloAlma.BajaCodigo,
    taArticuloAlma.BajaFecha,
    taArticuloAlma.CdadStock AS StockAlmacen,
    taArticuloAlma.PrecioCosteMedio AS PCPMAlmacen,
    taDctoCompra.Descrip,
    taCategoriaStock.Descrip,
    taCategoriaPieza.Descrip,
    taHistorico.Marca AS Marca,
    taHistorico.PrecioCosteMedio AS PrecioCosteMedio,
    taHistorico.TradeClub AS TradeClub,
    CASE WHEN taArticuloPrecio.Precioventa > 0 THEN
    taArticuloPrecio.Precioventa
    ELSE       taArticulo.PrecioVenta END AS PrecioVenta,
    COALESCE ((SELECT PrecioCoste FROM taArticuloProv WHERE taArticuloProv.NumInterno = taArticulo.NumInterno AND taArticuloProv.Proveedor = taArticulo.Proveedor),0.00) AS PrecioCompra,
    taHistorico.CategoriaStock AS CategoriaStock,
    taHistorico.StockFinal AS CantidadStock,
    CASE
    WHEN taHistorico.StockFinal <= 0 THEN 0.00
    WHEN taHistorico.StockFinal IS NULL THEN 0.00
    ELSE taHistorico.StockFinal
    END AS CdadStock,
    taHistorico.FamiliaInt AS FamiliaInt,
    taHistorico.FamiliaProv AS FamiliaProv,
    taHistorico.GrupoCont AS GrupoCont,
    taHistorico.ClaseProducto AS ClaseProducto,
    COALESCE (taHistorico.GrupoDctoCompra,'') AS GrupoDctoCompra,
    taHistorico.CodigoCategoria AS CodigoCategoria,
    ( CASE taArticulo.TieneConsigna
    WHEN 1 THEN
    COALESCE ((SELECT taArticuloProv.PrecioCoste FROM taArticuloProv, taArticulo Consigna
    WHERE Consigna.NumInterno = taArticulo.ReferenciaConsigna AND
    taArticuloProv.NumInterno = Consigna.NumInterno AND
    taArticuloProv.Proveedor = Consigna.Proveedor),0.00)
    ELSE 0.00
    END ) * 1 AS PrecioCompraConsigna,
    ( CASE taArticulo.TieneConsigna
    WHEN 1 THEN
    COALESCE ((SELECT Consigna.PrecioVenta FROM taArticulo Consigna
    WHERE Consigna.NumInterno = taArticulo.ReferenciaConsigna),0.00)
    ELSE 0.00
    END ) * 1 AS PrecioVentaConsigna,
    dbo.fn_ICarDMS_ConvertDateTime ('31-07-2013 23:59:59.000') AS ad_fecha,
    ( CASE taArticulo.TieneConsigna
    WHEN 1 THEN
    CASE WHEN ( SELECT histoprecio.precioCompraTarifa
    FROM taHistorico histoprecio
    WHERE histoprecio.Emp = taHistorico.emp AND
    histoprecio.NumIntHistorico = ( SELECT MAX (histomaxnum.NumIntHistorico)
    FROM taHistorico histomaxnum
    WHERE histomaxnum.Emp = '001' AND histomaxnum.Almacen = '11' AND histomaxnum.NumIntArticulo = taArticulo.ReferenciaConsigna AND
    histomaxnum.FechaHoraCreacion = ( SELECT MAX (histomaxfecha.FechaHoraCreacion)
    FROM taHistorico histomaxfecha
    WHERE histomaxfecha.Emp = '001' AND histomaxfecha.Almacen = '11' AND histomaxfecha.NumIntArticulo = taArticulo.ReferenciaConsigna AND
    histomaxfecha.FechaHoraCreacion <= year('31-07-2013 23:59:59.000') * 10000000000 + month('31-07-2013 23:59:59.000') * 100000000 + day('31-07-2013 23:59:59.000') * 1000000 + 235959
    ) )
    ) <> 0 THEN ( SELECT histoprecio.precioCompraTarifa
    FROM taHistorico histoprecio
    WHERE histoprecio.Emp = taHistorico.emp AND
    histoprecio.NumIntHistorico = (
    SELECT MAX (histomaxnum.NumIntHistorico)
    FROM taHistorico histomaxnum
    WHERE histomaxnum.Emp = '001' AND histomaxnum.Almacen = '11' AND histomaxnum.NumIntArticulo = taArticulo.ReferenciaConsigna AND
    histomaxnum.FechaHoraCreacion = (
    SELECT MAX (histomaxfecha.FechaHoraCreacion)
    FROM taHistorico histomaxfecha
    WHERE histomaxfecha.Emp = '001' AND histomaxfecha.Almacen = '11' AND histomaxfecha.NumIntArticulo = taArticulo.ReferenciaConsigna AND
    histomaxfecha.FechaHoraCreacion <= year('31-07-2013 23:59:59.000') * 10000000000 + month('31-07-2013 23:59:59.000') * 100000000 + day('31-07-2013 23:59:59.000') * 1000000 + 235959
    ) )
    )              ELSE
    COALESCE ((SELECT taArticuloProv.PrecioCoste FROM taArticuloProv, taArticulo Consigna
    WHERE Consigna.NumInterno = taArticulo.ReferenciaConsigna AND
    taArticuloProv.NumInterno = Consigna.NumInterno AND
    taArticuloProv.Proveedor = Consigna.Proveedor),0.00)
    END
    ELSE 0.00
    END ) * 1 as PrecioCosteMedioConsigna,
    taArticuloAlma.ultCoste,
    1 as consigna,
    taCaducidad.Descrip,
    taarticulo.codigotipo,
    taarticulo.indicadorpgr,
    taClaseProducto.Descrip,
    taArticulo.Caducidad
    FROM taHistorico
    LEFT OUTER JOIN tgGrupoCont ON taHistorico.GrupoCont = tgGrupoCont.GrupoCont
    LEFT OUTER JOIN taFamProveedor ON taHistorico.Marca = taFamProveedor.Marca AND taHistorico.FamiliaProv = taFamProveedor.Codigo 
    LEFT OUTER JOIN taFamInterna ON taHistorico.Marca = taFamInterna.Marca AND taHistorico.FamiliaInt = taFamInterna.Codigo
    LEFT OUTER JOIN taCategoriaStock ON taHistorico.Emp = taCategoriaStock.Emp AND taHistorico.Marca = taCategoriaStock.Marca AND taHistorico.CategoriaStock = taCategoriaStock.Codigo
    LEFT OUTER JOIN taclaseproducto ON taHistorico.Marca = taclaseproducto.Marca AND taHistorico.claseproducto = taclaseproducto.Codigo 
    LEFT OUTER JOIN taCategoriaPieza ON taHistorico.Marca = taCategoriaPieza.Marca AND taHistorico.CodigoCategoria = taCategoriaPieza.Codigo,
    taArticuloAlma 
    LEFT OUTER JOIN taArticuloPrecio ON (taArticuloAlma.NumInterno = taArticuloPrecio.NumInterno AND taArticuloAlma.Emp = taArticuloPrecio.Emp AND taArticuloAlma.Almacen = taArticuloPrecio.Almacen), 
    taArticulo
    LEFT OUTER JOIN taDctoCompra ON taArticulo.Marca = taDctoCompra.Marca AND taArticulo.Proveedor = taDctoCompra.Proveedor AND
    taArticulo.GrupoDctoCompra = taDctoCompra.GrupDctoComp AND
    taDctoCompra.TipoPedido IN ( SELECT tipopedido FROM tgalma where emp = '001' and almacen = '11' )
    LEFT OUTER JOIN taCaducidad  ON taArticulo.CodigoCaducidad = taCaducidad.Codigo,
    tgEmpresa,
    tgAlma,
    tgMarca
    WHERE taArticuloAlma.Emp = '001' AND
    taArticuloAlma.Almacen = '11' AND
    taArticuloAlma.NumInterno IN (SELECT DISTINCT NumIntArticulo FROM taHistorico
                                                                                                                                 WHERE taHistorico.Emp = '001' AND
                                                                                                                                 taHistorico.Almacen = '11' AND
                                                                                                                                 taHistorico.FechaHoraCreacion <= year ('31-07-2013 23:59:59.000') * 10000000000 + month('31-07-2013 23:59:59.000') * 100000000 + day ('31-07-2013 23:59:59.000') * 1000000 + 235959) AND
    taHistorico.emp = '001' AND
    taHistorico.NumIntHistorico = (SELECT MAX (taHistorico.NumIntHistorico) FROM taHistorico 
                                                                                                                                 WHERE taHistorico.Emp = '001' AND 
                                                                                                                                 taHistorico.Almacen = '11' AND 
                                                                                                                                  taHistorico.NumIntArticulo = taArticuloAlma.NumInterno AND
    ---------------------------
                                                                                                                                 taHistorico.FechaHoraCreacion = (SELECT MAX (taHistorico.FechaHoraCreacion) FROM taHistorico 
                                                                                                                                                                                                                                                                              WHERE taHistorico.Emp = '001' AND 
                                                                                                                                                                                                                                                                              taHistorico.Almacen = '11' AND 
                                                                                                                                                                                                                                                                              taHistorico.NumIntArticulo = taArticuloAlma.NumInterno AND
                                                                                                                                                                                                                                                                              taHistorico.FechaHoraCreacion <= year ('31-07-2013 23:59:59.000') * 10000000000 + month('31-07-2013 23:59:59.000') * 100000000 + day ('31-07-2013 23:59:59.000') * 1000000 + 235959)) 
    -------------
    AND
    taHistorico.StockFinal <> 0          AND
    taArticuloAlma.NumInterno = taArticulo.NumInterno AND 
    taArticulo.EsConsigna = 0 AND
    taArticulo.NoAlmacenada = 0 AND
    taArticuloAlma.Emp = tgEmpresa.Emp AND
    taArticuloAlma.Emp = tgAlma.Emp AND 
    taArticuloAlma.Almacen = tgAlma.Almacen AND
    taArticulo.Marca = tgMarca.Marca
    Entre les tiret c'est ou je veux faire la modification.

    Avec la requête de base, si je l' execute sur tout notre base de donnée il faut 2h pour avoir le résultat, si je modifie la ligne (en top1) j'ai le résultat en 3 minutes. C'est pour ca que je pose la question

    guigui69

  5. #5
    Modérateur

    Profil pro
    dba
    Inscrit en
    Janvier 2010
    Messages
    5 643
    Détails du profil
    Informations personnelles :
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : dba

    Informations forums :
    Inscription : Janvier 2010
    Messages : 5 643
    Points : 13 092
    Points
    13 092
    Par défaut
    Citation Envoyé par guigui69 Voir le message
    Avec la requête de base, si je l' execute sur tout notre base de donnée il faut 2h pour avoir le résultat, si je modifie la ligne (en top1) j'ai le résultat en 3 minutes. C'est pour ca que je pose la question
    D'accord, mais vous obtenez bien le même résultat !
    c'est juste le temps d’exécution qui change ?

    Dans ce cas, oui, il y a une différence, tout simplement car ce ne sont pas les mêmes requêtes, et en l’occurrence pas les mêmes plans d’exécution.

    Dans certains cas en effet, la requête avec TOP(1) pourra sembler plus rapide, mais bien souvent elle engendre un plus grand nombre de lectures.

  6. #6
    Membre du Club
    Profil pro
    Inscrit en
    Octobre 2006
    Messages
    816
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2006
    Messages : 816
    Points : 49
    Points
    49
    Par défaut
    Oui j'obtiens bien le même résultat

    Oui le temps exécution est vraiment réduit.

Discussions similaires

  1. Requête SELECT . . . WHERE X = (Select max(X))
    Par Taylorised dans le forum Requêtes et SQL.
    Réponses: 13
    Dernier message: 13/06/2012, 16h20
  2. requete imbriquée sur un select max()
    Par letoulouzin31 dans le forum Oracle
    Réponses: 2
    Dernier message: 20/01/2009, 11h01
  3. Différence entre un select max et un select top 1
    Par Delphi-ne dans le forum MS SQL Server
    Réponses: 2
    Dernier message: 24/06/2008, 09h05
  4. requete sql en vba avec un select MAX
    Par alexkickstand dans le forum VBA Access
    Réponses: 2
    Dernier message: 29/05/2007, 15h59
  5. [SQL] requete select max
    Par kabikou dans le forum Requêtes et SQL.
    Réponses: 9
    Dernier message: 19/10/2005, 16h18

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo