简体   繁体   English

MySQL跨多列计数,带有子查询,带有一个结果查询

[英]MySQL count across multiple columns, with subquery, with one result query

I have a table (kt2020) with fields (task1,task2,..pts,user,date).我有一个包含字段(task1、task2、..pts、user、date)的表(kt2020)。 The same task can appear in multiple columns.同一任务可以出现在多个列中。 To do a count by tasks, I have the subquery:要按任务进行计数,我有子查询:

SELECT
    task,
    count(*)
FROM     (SELECT task1 AS task FROM kt2020 UNION ALL
          SELECT task2 AS task FROM kt2020 UNION ALL
          SELECT task3 AS task FROM kt2020 UNION ALL
          SELECT task4 AS task FROM kt2020 UNION ALL
          SELECT task5 AS task FROM kt2020 UNION ALL
          SELECT task6 AS task FROM kt2020 UNION ALL
          SELECT task7 AS task FROM kt2020
) t

group by task

What I'd like now is to create an outer query that further filters by user and date;我现在想要的是创建一个外部查询,进一步按用户和日期过滤; smtg like this: smtg 像这样:

WHERE STR_TO_DATE(date, '%Y-%m-%d') >= CURDATE() - INTERVAL 7 DAY and user = 'username'

That would give me a result of tasks over the last 7 days, from user 'username'.这将为我提供过去 7 天内来自用户“用户名”的任务结果。 Right now, these outer fields are hidden to the current query, and I don't know how to access 'date' or 'user' in the same query.现在,这些外部字段对当前查询是隐藏的,我不知道如何在同一查询中访问“日期”或“用户”。

I guess I could bang out something long and cumbersome, but I'm sure there's a way that uses a common function I'm not aware of?我想我可以敲出一些又长又麻烦的东西,但我确定有一种方法可以使用我不知道的通用功能?

One option is the subquery to return date and user and then use a WHERE clause to filter:一种选择是返回dateuser的子查询,然后使用WHERE子句进行过滤:

SELECT
    task,
    count(*)
FROM     (SELECT task1 AS task, date, user FROM kt2020 UNION ALL
          SELECT task2 AS task, date, user FROM kt2020 UNION ALL
          SELECT task3 AS task, date, user FROM kt2020 UNION ALL
          SELECT task4 AS task, date, user FROM kt2020 UNION ALL
          SELECT task5 AS task, date, user FROM kt2020 UNION ALL
          SELECT task6 AS task, date, user FROM kt2020 UNION ALL
          SELECT task7 AS task, date, user FROM kt2020
) t
WHERE STR_TO_DATE(date, '%Y-%m-%d') >= CURDATE() - INTERVAL 7 DAY and user = 'username'
group by task

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM