从表中执行选择计数(col),max(col),column_name_data

时间:2012-11-13 13:45:58

标签: mysql sql

我如何做select count(artc_id) as cval, max(srt_id) as maxval, artc_title from table where artc_pub = 1

所以我可以获得如下结果:

       cval | maxval | artc_title | artc_pub
    -----------------------------------------
       4         4     Title 1         1 
                       Title 2         1
                       Title 3         1
                       Title 4         1

我的部分表格位于

之下
artc_id | srt_id | artc_title | artc_pub
-----------------------------------------
   1         1     Title 1         1 
   2         2     Title 2         1
   3         3     Title 3         1
   4         4     Title 4         1
   1         5     Title 1         2
   2         6     Title 2         2

我试过了select count(artc_id) as cval, max(srt_id) as maxval, artc_title from table where artc_pub = 1,但这只给了我一行第一个标题。我想这里必须有一个以上的普通选择。

以下所有答案都给我这样的结果:

cval;maxval;artc_title
1   ;     1; Title 1
1   ;     2; Title 2
1   ;     3; Title 3
1   ;     4; Title 4
1   ;     5; Title 5

不像我在问题中提到的那样。

5 个答案:

答案 0 :(得分:1)

我认为有2个查询更好,一个用于聚合,一个用于标题:

SELECT COUNT(*) AS cval, 
       MAX(srt_id) AS maxval
FROM table 
WHERE artc_pub = 1 ;

SELECT artc_title 
FROM table 
WHERE artc_pub = 1 ;

您还可以使用GROUP_CONCAT()功能将标题合并为一行:

SELECT COUNT(*) AS cval, 
       MAX(srt_id) AS maxval,
       GROUP_CONCAT(artc_title ORDER BY srt_id SEPARATOR ', ') 
           AS artc_title  
FROM table 
WHERE artc_pub = 1 ;

您也可以将这两者与一个联接组合在一起,但是您将返回大量重复数据:

SELECT ag . cval, 
       ag . maxval, 
       t  . artc_title 
FROM 
    ( SELECT COUNT(*) AS cval, 
             MAX(srt_id) AS maxval
      FROM table 
      WHERE artc_pub = 1 
    ) AS ag
  CROSS JOIN
    table AS t 
WHERE t.artc_pub = 1 ;

如果MySQL得到了窗口函数(乐观主义者读过:它会有的话),上面的内容将写成:

SELECT COUNT(*) OVER ()    AS cval, 
       MAX(srt_id) OVER () AS maxval, 
       artc_title 
FROM table 
WHERE artc_pub = 1 ;

答案 1 :(得分:0)

您应该可以在此使用GROUP BY按“文章标题”对结果进行分组:

SELECT
    COUNT(artc_id) AS cval,
    MAX(srt_id) AS maxval,
    artc_title
FROM
    table
WHERE
    artc_pub = 1
GROUP BY
    artc_title
ORDER BY
    artc_title;

答案 2 :(得分:0)

GROUP BY artc_title喜欢这样:

select 
  count(artc_id) as cval, 
  max(srt_id) as maxval, 
  artc_title 
from table 
where artc_pub = 1
GROUP BY artc_title

答案 3 :(得分:0)

您错过了分组字词

 SELECT count(artc_id) AS cval, max(srt_id) AS maxval, artc_title 
       FROM table
       WHERE artc_pub = 1
       GROUP BY artc_title

答案 4 :(得分:0)

您是否尝试过>>

select count(artc_id) as cval, max(srt_id) as maxval, artc_title from table where artc_pub = 1 Group By artc_title

我希望这会奏效。