如何将行计数作为列

时间:2013-08-24 15:29:11

标签: php sql sqlite count distinct

所以我有这样的查询

SELECT DISTINCT colB FROM tbl WHERE colA = "foo" LIMIT 0, 20

让我得到一个最大的数组。 colA匹配"foo"的20条记录,但没有重复记录。每个数组条目都包含一个包含值colB的关联数组,如

0 => array(
       'colB' => 'some_value',
     ),
1 => array(
       'colB' => 'other_value',
     )

我还可以获得COUNT() colB值吗?我的意思是:

SELECT COUNT() as cbCount FROM tbl WHERE colA = "foo" AND colB = "some_value"
SELECT COUNT() as cbCount FROM tbl WHERE colA = "foo" AND colB = "other_value"

但作为另一个数组字段包含在第一个查询中,如:

0 => array(
       'colB' => 'some_value',
       'cbCount' => 5,
     ),
1 => array(
       'colB' => 'other_value',
       'cbCount' => 2,
     )

2 个答案:

答案 0 :(得分:1)

您需要做的就是使用GROUP BY子句

SELECT  colB,
        COUNT(colB) AS cbCount
FROM    tableName
WHERE   colA = 'Foo'
GROUP   BY colB

答案 1 :(得分:1)

您需要将Group ByCount -

一起使用
SELECT 
        colB, count(colB) as cbCount
FROM    
        tbl 
WHERE  
        colA = 'foo' 
GROUP BY 
        colB 
LIMIT 
        0, 20

此查询将获取前20行,根据colB的不同值对其进行分组并计算其数量。