Visualizzazione dei risultati da 1 a 2 su 2
  1. #1
    Utente di HTML.it L'avatar di nicola75ss
    Registrato dal
    Nov 2004
    Messaggi
    12,922

    [Mysql] Query a campi incrociati

    Ciao a tutti. Non riesco a scrivere una query a campi incrociati.

    In pratica avendo un campo di tipo date e una serie di messaggi come faccio a stilare un report del genere, dove mi mostri il totale di messaggi per mese/anno.

    es.
    codice:
    anno    gen  feb...           dic
    2004     0      3                2
    2005     4      2                3
    2006     2      0                1
    Io ho scritto questa query

    codice:
    select year(datas) as anno,
    case month(datas) when 1 then count(mesg) else 0 end as gen,
    case month(datas) when 2 then count(mesg) else 0 end as feb,
    case month(datas) when 3 then count(mesg) else 0 end as mar,
    case month(datas) when 4 then count(mesg) else 0 end as apr,
    case month(datas) when 5 then count(mesg) else 0 end as mag,
    case month(datas) when 6 then count(mesg) else 0 end as giu,
    case month(datas) when 7 then count(mesg) else 0 end as lug,
    case month(datas) when 8 then count(mesg) else 0 end as ago,
    case month(datas) when 9 then count(mesg) else 0 end as sett,
    case month(datas) when 10 then count(mesg) else 0 end as ott,
    case month(datas) when 11 then count(mesg) else 0 end as nov,
    case month(datas) when 12 then count(mesg) else 0 end as dic
    from messaggi
    group by anno
    order by anno
    Ottengo la mia bella tabella con gli anni e i mesi ma i conteggi son sbagliati, nel senso che mi assegna il totale di ciascun anno a un solo mese. Immagino che il problema sia dovuto al fatto che raggruppo per anno, però, se faccio select extract(year_month from datas ) eccetera, ovviamente mi crea una riga per ogni mese/anno diverso che trova.

    Come risolvo? Grazie.

  2. #2
    Utente di HTML.it L'avatar di nicola75ss
    Registrato dal
    Nov 2004
    Messaggi
    12,922
    Risolto.

    codice:
    select year(datas) as anno,
    sum(if(month(datas) = 1,1,0)) as gen,
    sum(if(month(datas) = 2,1,0)) as feb,
    sum(if(month(datas) = 3,1,0)) as mar,
    sum(if(month(datas) = 4,1,0)) as apr,
    sum(if(month(datas) = 5,1,0)) as mag,
    sum(if(month(datas) = 6,1,0)) as giu,
    sum(if(month(datas) = 7,1,0)) as lug,
    sum(if(month(datas) = 8,1,0)) as ago,
    sum(if(month(datas) = 9,1,0)) as sett,
    sum(if(month(datas) = 10,1,0)) as ott,
    sum(if(month(datas) = 11,1,0)) as nov,
    sum(if(month(datas) = 12,1,0)) as dic
    from messaggi
    group by anno

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 © 2025 vBulletin Solutions, Inc. All rights reserved.