Domanda

  • Sto creando un JasperReport usando iReport e, in quanto tale, sono limitato * a una query SQL.

  • Ho una tabella "statistiche", con le colonne "nome" (VARCHAR), "conteggio" (INTEGER) e "datetime" (DATETIME).

  • È abbastanza semplice ottenere la somma della colonna 'count' quando il 'nome' era " test " per l'ultimo giorno, e allo stesso modo per l'ultima settimana e mese (vedi sotto)

Dichiarazione SQL funzionante:


SELECT
  SUM(count)as 'today'
FROM
  statistics
WHERE
   name = "test"
  AND $P{oneDayAgo} <= datetime
  AND datetime <= $P{now}
  • Tuttavia, poiché ho una sola istruzione SQL con cui lavorare, devo combinarle in qualche modo. Ho provato a usare UNION (come muggito) ma questo non ha funzionato.

Istruzione SQL non riuscita:

SELECT
     SUM(count)as 'today'
FROM
     statistics
WHERE
     name = "test"
 AND $P{oneDayAgo} <= datetime
 AND datetime <= $P{now}
UNION
SELECT
     SUM(count)as 'thisWeek'
FROM
     statistics
WHERE
     name = "test"
 AND $P{oneWeekAgo} <= datetime
 AND datetime <= $P{now}
UNION
SELECT
     SUM(count)as 'thisMonth'
FROM
     statistics
WHERE
     name = "test"
 AND $P{oneMonthAgo} <= datetime
 AND datetime <= $P{now}

(*) si possono aggiungere ulteriori query solo per grafici o campi incrociati, nessuno dei quali serve al mio scopo.

È stato utile?

Soluzione

sum (case when -condition- then count else 0 end)

SELECT
  SUM(case when $P{oneDayAgo} <= datetime then count else 0 end) as 'today',
  SUM(case when $P{oneWeekAgo} <= datetime then count else 0 end) as 'thisweek',
  SUM(count) as 'thismonth'
FROM
  statistics
WHERE
   name = "test"
  AND $P{oneMonthAgo} <= datetime
  AND datetime <= $P{now}

nota che se hai bisogno di medie, assicurati di sostituire NULL con 0.

Altri suggerimenti

Le query UNION dovrebbero produrre le stesse colonne (nome, tipo). Impostare le colonne non utilizzate su NULL o utilizzare una colonna di differenziazione:

SELECT
     SUM(count) as `total`,
     'today' as `when`
FROM
     statistics
WHERE
     name = "test"
 AND $P{oneDayAgo} <= datetime
 AND datetime <= $P{now}
UNION
SELECT
     SUM(count) as `total`,
     'thisWeek' as `when`
FROM
     statistics
WHERE
     name = "test"
 AND $P{oneWeekAgo} <= datetime
 AND datetime <= $P{now}
UNION
SELECT
     SUM(count) as `total`,
     'thisMonth' as `when`
FROM
     statistics
WHERE
     name = "test"
 AND $P{oneMonthAgo} <= datetime
 AND datetime <= $P{now}

Hai 2 opzioni:

1) Rimuovi la parte 'as' di ogni query e verrà visualizzata come 1 colonna che non avrà un nome

2) Crea una tabella temporanea e inserisci quelle righe in una tabella temporanea, quindi esegui una query sulla tabella temporanea

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top