我正在使用iReport创建一个JasperReport,因此,我对一个SQL查询的限制*。
我有一个'统计'表,带有'name'(VARCHAR),'count'(INTEGER)和'datetime'(DATETIME)列。
当'name'为最后一天的“test”时,很容易获得'count'列的总和,并且类似于上周和月(见下文)
工作SQL语句:
SELECT
SUM(count)as 'today'
FROM
statistics
WHERE
name = "test"
AND $P{oneDayAgo} <= datetime
AND datetime <= $P{now}
SQL语句失败:
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}
(*)可以只为图表或交叉表添加其他查询,这些查询都不能满足我的目的。
答案 0 :(得分:4)
总和(情况 - 条件 - 然后计数,否则0结束)
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}
请注意,如果您需要平均值,请务必将NULL替换为0。
答案 1 :(得分:0)
UNION'd查询应生成相同的列(名称,类型)。将未使用的列设置为NULL或使用差异列:
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}
答案 2 :(得分:0)
您有两个选择:
1)删除每个查询的“as”部分,然后它将作为1列没有名称
2)创建临时表并将这些行插入临时表,然后查询临时表