有限集团

时间:2015-11-06 21:05:34

标签: mysql sql group-by

我有以下数据库:

date, connection_id, connection_status, file_requested
2015,     1234      ,      OK          ,file1
2015,     1234      ,      OK          ,file2
2015,     1235      ,      OK          ,file2
2014,     1236      ,      FAILURE     ,file1

我当前的查询给出了每个file_requested每个连接状态的每个日期的不同连接数,如下所示:

select date, count(distinct(connection_id)), connection_status, 
file_requested from database group by date, connection_status, file_requested;


date,     count     , connection_status, file_requested
2015,     1         ,      OK          ,file1
2015,     1         ,      OK          ,file2
2014,     1         ,      FAILURE     ,file1

但是,我还想要每个连接的每个日期的不同连接数,如下所示。 (我知道我可以在一个单独的查询中执行此操作,只需将#ad; group by file_requested" - 但我不想要这样做。)

date,     count     , connection_status, file_requested
2015,     1         ,      OK          ,file1
2015,     1         ,      OK          ,file2
2014,     1         ,      FAILURE     ,file1
2015,     2         ,      OK          ,  --
2014,     1         ,      FAILURE     ,  --

这甚至可能吗?

1 个答案:

答案 0 :(得分:0)

我认为没有办法改变group by。您可以使用union

实现您想要的效果
(select 1 as sort_column, date, count(distinct connection_id), connection_status, 
file_requested from database group by date, connection_status, file_requested)
union all
(select 2 as sort_column, date, count(distinct connection_id), connection_status, 
'--' as file_requested from database group by date, connection_status)
order by sort_column;

distinct不是函数,因此不需要括号。