dimanche 26 avril 2015

Duplicated rows in a Join Query SQL Server 2005

Dear I have the following problem. I need to get a list of products from a SQL Server 2005 database. Turns out I should first calculate the stock, which is related to many tables and then make calculations regarding other tables. The problem is that query shows me that I found records separately and have not managed to group (Investigating Google here and in whole, in addition to testing) so I decided to consult:

PD: I leave aside the products that are in the cellar [cod_bodeg] having lower value 10687 to 10000

PD2: The database belongs to a Chilean ERP and they do not provide the documentation of the model. All I know here I researched on my own.

Table Articles (ART)

  • NREGUIST ( ID OF ART )

Table Cellar (CHOI)

  • NUMREG ( ID OF CELL )
  • STK_FISICO ( Stock of Article in that Cell )

Table NOTDE_DB (ARTICLES SELLED)

  • NCODART ( INDEX to NREGUIST of ART )
  • cantidad ( Qty of Article that is selled in the invoice this is subtracted of the stock for calculate the qty)

Table STOCK

  • ARTICULO ( Index to NREGUIST of ART )
  • COD_BODEG ( INDEX to NUMREG of CHOI )

Table DSCTO

  • ID_ART ( INDEX to NREGUIST of ART )
  • DESCTO ( PRICE of ARTICLE )

This is my Query: What advice?

SELECT
    ROUND ( ISNULL( 
    ( 
    SELECT isnull( SUM( STOCK_DB.STK_FISICO ),0 )
        FROM 
            STOCK_DB
        JOIN CHOI_DB 
            ON STOCK_DB.cod_bodeg = CHOI_DB.numreg 
        WHERE 
            STOCK_DB.ARTICULO=ART_DB.nreguist 
            AND STOCK_DB.NUMEMPSTK=1 
            AND CHOI_DB.codigo NOT IN ('B98','B4','B6','B2')
    ) - ISNULL( 
            (
            SELECT 
                SUM(notde_db.cantidad - notde_db.cantdesp) 
            FROM 
                notde_db,notv_db 
            WHERE 
                notde_db.ncodart=ART_DB.nreguist 
                AND notde_db.terminado=0  
                AND notv_db.numreg=notde_db.numrecor 
            GROUP BY notde_db.ncodart 
            ) 
        ,0) , 0
    ), 0) as DISPONIBLE,
    [NOMBRE],
    [NREGUIST],
    [CODIGO],
    [IMPUTABLE],
    [XX],
    [UNIDMED], 
    ROUND([PRECVTA], 0) AS PRECVTA, 
    [NIVEL1], 
    [NIVEL2], 
    [NIVEL3],
    [NIVEL4], 
    [NIVEL5], 
    [NIVEL6], 
    [NIVEL7], 
    [NIVEL8], 
    [NIVEL9], 
    [CLASE1], 
    [CLASE2], 
    [CLASE3], 
    [CLASE4], 
    [ART_DISPON], 
    [OBS],
    ROUND(ISNULL([DESCT_DB].[DESCTO],0) ,0) as PRECIO2
FROM 
     [STOCK_DB], [ART_DB]
LEFT JOIN 
    [DESCT_DB] ON ([DESCT_DB].[IDART] = [ART_DB].[NREGUIST])
WHERE 
    tipo = 1 
    AND clase2 != 'XX' 
    AND clase4 != 'OFF'
    AND ([STOCK_DB].[cod_bodeg] != 10687 OR ( [STOCK_DB].[cod_bodeg] = 10687 AND [DESCT_DB].[DESCTO] > 10000))
ORDER BY 
    DISPONIBLE DESC

Thanks!

Aucun commentaire:

Enregistrer un commentaire