Visualizzazione dei risultati da 1 a 4 su 4
  1. #1
    Utente di HTML.it
    Registrato dal
    Sep 2007
    Messaggi
    1,171

    modifica query su due tabelle

    ho questa query che mi è stata consigliata sul form e funziona benissimo.
    Ora ho pero l'esigenza di modificarla per questo motivo:

    1- tabella A e tabella B contengono gli stessi campi.
    2- la query sotto non fa altro che abbinare in base al codice univoco i record.

    esempio :
    tabella A tabella B
    codice valore codice valore
    A 7 A 3
    B 9 C 2

    risultato:
    A 7 3
    B 9 0
    C 0 2

    ora nella prima tabella e nella seconda i record possono essere doppi:
    esempio :
    tabella A tabella B
    codice valore codice valore
    A 7 A 3
    B 9 C 2
    A 2 A 8
    ------------------------------------------------
    come si modifica la query sotto per sommare i valori tabella A e tabella B???

    ecco la query:
    SELECT codice, MAX(CASE WHEN tab = 1 THEN VALORE ELSE 0 END) AS va1
    FROM (SELECT CODICE, VALORE , 1 AS tab
    FROM dbo.DATABASE
    WHERE (PERIODO = '07/2010')
    UNION ALL
    SELECT CODICE,VALORE, 2 AS tab2
    FROM dbo.DATABASE2) AS t
    WHERE (PERIODO = '07/2010')
    GROUP BY CODICE,VALORE

  2. #2
    Utente di HTML.it L'avatar di nicola75ss
    Registrato dal
    Nov 2004
    Messaggi
    12,922
    codice:
    select codice,sum(valore) as totale from (
    select codice,valore from tab1 where ...
    union all
    select codice,valore from tab2 wehre ..) as t
    group by codice

  3. #3
    Utente di HTML.it
    Registrato dal
    Sep 2007
    Messaggi
    1,171
    funziona ma mi fa la somma di tutti ii record di quel codice.
    devo invece fare la somma all'interno delle tabelle:
    tabella A tabella B
    codice val codice val
    3 6 3 4
    3 3 3 3

    risultato
    CODICE tabella A tabella B
    3 9 7

  4. #4
    Utente di HTML.it L'avatar di nicola75ss
    Registrato dal
    Nov 2004
    Messaggi
    12,922
    codice:
    select codice,
    max(case when t=1 then totale else 0 end) as t1,
    max(case when t=2 then totale else 0 end) as t2
    from (
    select codice,sum(valore) as totale,1 as t from tab1 group by codice
    union all
    select codice,sum(valore), 2 as t from tab2 group by codice
    ) as t
    group by codice

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2026 vBulletin Solutions, Inc. All rights reserved.