选择mySQL中列中出现次数最多的值

时间:2016-02-18 14:28:38

标签: mysql sql

关注是样本表

SELECT Project
    ,count(Project) AS ProjectCount
    ,count(CASE STATUS
            WHEN 'Fixed'
                THEN 1
            ELSE NULL
            END) AS Fixed
    ,count(CASE STATUS
            WHEN 'Closed'
                THEN 1
            ELSE NULL
            END) AS Closed
FROM TABLE
GROUP BY Project;

我想要的是项目名称,每个项目的状态计数,每个项目的计数和状态'固定',项目状态'已关闭'和修复了大多数项目的修复者。

除了粗体部分我能够让其他人使用以下查询

Project, ProjectCount, Fixed, Closed, Fixcer    
P1,          3,          2,     1,     Nimna

我需要输出

awk '/^[^[:space:]]/{print "Result : " $0}'

2 个答案:

答案 0 :(得分:1)

这里的问题是将选择第一个修复程序,大多数出现在项目中,但不处理关系。所以你应该提供一个处理关系的规则。

<强> SQL Fiddle Demo

SELECT Project
    ,count(Project) AS ProjectCount
    ,count(CASE STATUS
            WHEN 'Fixed'
                THEN 1
            ELSE NULL
            END) AS Fixed
    ,count(CASE STATUS
            WHEN 'Closed'
                THEN 1
            ELSE NULL
            END) AS Closed
    , (SELECT fixer
       FROM Table1 B
       WHERE A.`Project` = B.`Project`
       GROUP BY fixer
       ORDER BY COUNT(*) DESC
       LIMIT 1
      ) as Fixer
FROM TABLE1 A
GROUP BY Project;

<强>输出

| Project | ProjectCount | Fixed | Closed | Fixer |
|---------|--------------|-------|--------|-------|
|      P1 |            3 |     2 |      1 | Nimna |
|      P2 |            1 |     1 |      0 |  Amal |
|      P3 |            1 |     1 |      0 | Nimal |
|      P4 |            1 |     1 |      0 |  Amal |

答案 1 :(得分:0)

如果您只想要项目的信息次数最多,请使用此查询:

SELECT 
    P1.Project, 
    COUNT(*) ProjectCount, 
    SUM( P1.Status = 'Fixed' ) Fixed, 
    SUM( P1.Status = 'Closed' ) Closed, 
    ( SELECT COUNT(*) cnt
      FROM Project P2
      WHERE P1.Project = P2.Project AND P2.Status = 'Fixed'
      GROUP BY P2.Fixer
      ORDER BY cnt DESC
      LIMIT 1 )
FROM Project P1
GROUP BY P1.Project;

如果您想要所有项目的信息,请使用以下信息:

SELECT 
    P1.Project, 
    COUNT(*) ProjectCount, 
    SUM( P1.Status = 'Fixed' ) Fixed, 
    SUM( P1.Status = 'Closed' ) Closed, 
    ( SELECT COUNT(*) cnt
      FROM Project P2
      WHERE P1.Project = P2.Project AND P2.Status = 'Fixed'
      GROUP BY P2.Fixer
      ORDER BY cnt DESC
      LIMIT 1 )
FROM Project P1
GROUP BY P1.Project
ORDER BY ProjectCount DESC
LIMIT 1;