1

是否可以在单个查询中执行多个聚合函数

我知道谁可以使用

SELECT SUM(value) FROM mytable WHERE date  between '2012-05-01' AND '2012-06-01'

我一直在尝试做一个例子

CREATE TABLE mytable
    (id varchar(10), value int, `date` date, situation varchar(10) ) ;

INSERT INTO mytable
    (id, value, date, situation)
VALUES
    ('id0', 1338, '2012-05-14','Urgent'),
    ('id0', 3572, '2012-05-13','Urgent'),
    ('id0', 3232, '2012-05-06','Urgent'),
    ('id0', 3068, '2012-05-05','Post'),
    ('id0', 3363, '2012-05-04','Urgent'),
    ('id0', 2022, '2012-04-28','Anual'),
    ('id0', 3193, '2012-04-24','Post')

但是是否可以使用相同的查询来获取其他聚合值?

SELECT SUM(value),SUM(value),Count(*) FROM mytable WHERE date  between '2012-05-01' AND '2012-06-01', WHERE date  between '2012-05-01' AND '2012-10-01', Where situation like 'Urgent' 

而不是 3 个查询:

SELECT SUM(value) FROM mytable WHERE date  between '2012-05-01' AND '2012-06-01'
SELECT SUM(value) FROM mytable WHERE date  between '2012-05-01' AND '2012-10-01'
SELECT Count(*)   FROM mytable Where situation like 'Urgent'
4

2 回答 2

3

用例

select
    sum(case when date between '2012-05-01' AND '2012-06-01' then value else 0 end) as sum1,
    sum(case when date between '2012-05-01' AND '2012-10-01' then value else 0 end) as sum2,
    sum(case when situation like 'Urgent' then 1 else 0 end) as count1
from mytable
于 2012-10-16T17:02:37.090 回答
1

你可以

SELECT 
SUM(CASE WHEN date  between '2012-05-01' AND '2012-06-01' THEN value ELSE 0 END)
as sum1,
SUM(CASE WHEN date  between '2012-05-01' AND '2012-10-01' THEN value ELSE 0 END)
as sum2,
COUNT(CASE WHEN situation like 'Urgent%' THEN 1 ELSE 0 END)
as cnt1
FROM mytable Where situation like 'Urgent%' OR  date  between '2012-05-01' AND '2012-10-01'

我猜你错过了 % 在 like:like 'Urgent%'中,不是like 'Urgent'

于 2012-10-16T17:02:56.737 回答