在MySQL中应用查询之前过滤表

时间:2017-05-15 13:54:41

标签: mysql

我有一个名为push_message_info的mysql表,我想过滤然后计算一些结果。获得结果的查询是:

SELECT p.pending, s.success, t.total
FROM 
    (SELECT count(*) AS pending FROM push_message_info WHERE served < total) AS p,
    (SELECT count(*) AS success FROM push_message_info WHERE served = total) AS s,
    (SELECT count(*) AS total FROM push_message_info) AS t
;

事情是我想只计算最新的条目。由于它有一个名为submit_date的日期时间字段,我认为这样的事情会起作用:

SELECT p.pending, s.success, t.total
FROM 
    (SELECT * FROM push_message_info WHERE DATE(submit_date) > '2017-05-14') AS filtered
    (SELECT count(*) AS pending FROM filtered WHERE served < total) AS p,
    (SELECT count(*) AS success FROM filtered WHERE served = total) AS s,
    (SELECT count(*) AS total FROM filtered) AS t
;

但它让我错误:

  

ERROR 1146(42S02):表'unifiedpush.filtered'不存在

如何过滤/限制原始表格,以便我可以对该新表格应用其他查询?

3 个答案:

答案 0 :(得分:3)

您的查询一般不太好。 您可以通过一个简单的查询来完成所有这些子查询。

SELECT 
    SUM(CASE WHEN served < total THEN 1 ELSE 0 END) AS pending,
    SUM(CASE WHEN served = total THEN 1 ELSE 0 END) AS served,
    COUNT(*) as total
FROM push_message_info
WHERE DATE(submit_date) > '2017-05-14';

我已将count s(total除外)与SUM(CASE WHEN ... THEN 1 ELSE 0 END)切换为允许您进行条件计数。

答案 1 :(得分:1)

好吧,我可以告诉你我是如何完成这样的事情的。尝试:

import pandas as pd

csv_file = pd.read_csv('U:\\INSEE\\Data.csv',sep=';')
csv_file.to_excel('U:\\INSEE\\fichier.xlsx')

这应该能满足你的需要......

答案 2 :(得分:1)

查询中的问题是过滤后的别名的范围:从其他子查询中看不到它。

如果你真的想拥有它,你可以创建一个视图:

create view filtered as SELECT * FROM push_message_info WHERE DATE(submit_date) > '2017-05-14';

SELECT p.pending, s.success, t.total
FROM
    (SELECT count(*) AS pending FROM filtered WHERE served < total) AS p,
    (SELECT count(*) AS success FROM filtered WHERE served = total) AS s,
    (SELECT count(*) AS total FROM filtered) AS t;