我对SQL很陌生,我正在运行这样的东西来提取一些数据。但是目前我一次运行一个语句并将它们复制到excel。有没有办法一起运行所有这些?每个语句的级别相同,但count(ID)将不同。某些级别可能还有某些天没有任何数据。
select
count(ID), level
from table1
where createat >= "2013-11-22 00:00:00" and createat <= "2013-11-22 23:59:59"
group by level;
select
count(ID), level
from table1
where createat >="2013-11-23 00:00:00" and createat <= "2013-11-23 23:59:59"
group by level;
select
count(ID), level
from table1
where createat >= "2013-11-24 00:00:00" and createat <= "2013-11-24 23:59:59"
group by level;
感谢您的帮助!我希望更多地了解如何编写这些内容。
答案 0 :(得分:2)
SELECT
level,
COUNT(CASE WHEN createat>='2013-11-22' and createat<'2013-11-23' THEN id ELSE NULL END) AS day_1_count,
COUNT(CASE WHEN createat>='2013-11-23' and createat<'2013-11-24' THEN id ELSE NULL END) AS day_2_count,
COUNT(CASE WHEN createat>='2013-11-24' and createat<'2013-11-25' THEN id ELSE NULL END) AS day_3_count
FROM
table1
GROUP BY
level
WHERE
createat>='2013-11-22' and createat<'2013-11-25'
尽管如此,使用您需要的日期加入表格可能更有意义,而不是硬编码。
另外,请注意,SQL适用于固定数量的列,如果您想要一个查询3天然后重复使用5天,则不起作用。为此,您需要将其保留为每行一个结果。
答案 1 :(得分:2)
试试这个:
SELECT t.level, SUM(CASE WHEN DATE(createat) = '2013-11-22' THEN 1 ELSE 0 END) AS day1,
SUM(CASE WHEN DATE(createat) = '2013-11-23' THEN 1 ELSE 0 END) AS day2,
SUM(CASE WHEN DATE(createat) = '2013-11-24' THEN 1 ELSE 0 END) AS day3
FROM table1 t
WHERE DATE(t.createat) >= "2013-11-22" AND DATE(t.createat) <= "2013-11-24"
GROUP BY t.level;
或强>
SELECT t.level, SUM(CASE WHEN t.createat >= "2013-11-22 00:00:00" AND t.createat <= "2013-11-22 23:59:59" THEN 1 ELSE 0 END) AS day1,
SUM(CASE WHEN t.createat >= "2013-11-23 00:00:00" AND t.createat <= "2013-11-23 23:59:59" THEN 1 ELSE 0 END) AS day2,
SUM(CASE WHEN t.createat >= "2013-11-24 00:00:00" AND t.createat <= "2013-11-24 23:59:59" THEN 1 ELSE 0 END) AS day3
FROM table1 t
WHERE t.createat >= "2013-11-22 00:00:00" AND t.createat <= "2013-11-24 23:59:59"
GROUP BY t.level;
答案 2 :(得分:1)
您发布的查询的简单编辑是:
select count(ID), level
from table1
where createat >= "2013-11-22 00:00:00" and createat <= "2013-11-22 23:59:59"
group by level
union
select count(ID), level
from table1
where createat >="2013-11-23 00:00:00" and createat <= "2013-11-23 23:59:59"
group by level
union
select count(ID), level
from table1
where createat >= "2013-11-24 00:00:00" and createat <= "2013-11-24 23:59:59"
group by level
但是,如果您尝试获取每天的计数,级别值和日期,那么您可以使用如下查询:
SELECT COUNT(*), level, CAST(createat AS DATE)
FROM table1
GROUP BY level, CAST(createat AS DATE)