mysql GROUP BY显示所有对应的字段

时间:2018-09-20 10:33:31

标签: mysql

我的表格如下:

ID      EMP_ID      NAME        ACTIVITY_DATE       ACTIVITY_CODE

1       EMP01      ROCKY        2018-02-19          AC04  
2       EMP02      SMITH        2018-02-19          AC09
3       EMP02      SMITH        2018-02-19          AC10
4       EMP01      ROCKY        2018-02-20          AC04
5       EMP01      ROCKY        2018-02-20          AC04
6       EMP03      RICKY        2018-02-22          AC05
7       EMP03      RICKY        2018-02-22          AC07
8       EMP02      SMITH        2018-02-22          AC09

我想从查询结果中消除重复的日期,并按ID显示所有对应字段的顺序,我的表应类似于:

ID      EMP_ID      NAME        ACTIVITY_DATE    ACTIVITY_CODE     COUNT

1       EMP01      ROCKY        2018-02-19          AC04            3
4       EMP01      ROCKY        2018-02-20          AC04            2
6       EMP03      RICKY        2018-02-22          AC05            3

我已经尝试过以下查询:

SELECT ID, EMP_ID, NAME, ACTIVITY_DATE, ACTIVITY_CODE 
FROM emp_entries
GROUP BY ID, EMP_ID, NAME, ACTIVITY_DATE, ACTIVITY_CODE

但是不能消除重复的条目。

仅当我这样做时,它才起作用:

SELECT COUNT(ACTIVITY_DATE), ACTIVITY_DATE 
FROM emp_entries
GROUP BY ACTIVITY_DATE. 

但是它只显示一个字段。

4 个答案:

答案 0 :(得分:1)

您可以使用subqueryjoin来完成

   SELECT e1.id,e1.EMP_ID,e1.NAME,e1.ACTIVITY_DATE ,e1.ACTIVITY_CODE,e2.cnt 
    FROM emp_entries e1
    JOIN(
        SELECT COUNT(ACTIVITY_DATE) as cnt,MIN(id) AS mId
        FROM emp_entries
        GROUP BY ACTIVITY_DATE) e2 
    ON e2.mId=e1.id

答案 1 :(得分:1)

Use inner join and subquery:

select e1.ID ,e1.EMP_ID ,e1.NAME,e1.ACTIVITY_DATE,e1.ACTIVITY_CODE,e2.count 
from emp_entries e1 inner join
(
SELECT COUNT(ACTIVITY_DATE) as count, ACTIVITY_DATE, min(id) as mid
FROM emp_entries
GROUP BY ACTIVITY_DATE
) e2 on e1.id=e2.mid

答案 2 :(得分:0)

您需要使用Distinct关键字来消除重复项。

选择不同的col1,col 2等

答案 3 :(得分:0)

在按该表分组时,必须使用分组函数,在您的示例中,我看到您显示了第一个元素,因此,我认为此查询将为您工作。

SELECT 
    MIN(ID) as ID,
    MIN(EMP_ID) as EMP_ID,
    MIN(NAME) as NAME,
    ACTIVITY_DATE, 
    MIN(ACTIVITY_CODE) as ACTIVITY_CODE,
    COUNT(ID) as COUNT
FROM emp_entries
GROUP BY ACTIVITY_DATE