简单的psql计数查询

时间:2013-07-17 15:07:55

标签: sql postgresql

我对postgresql很新,并希望从我们的表中生成一些摘要数据

我们有一个简单的留言板 - 表名messages,其中包含元素ctg_uid。每个ctg_uid对应表categories中的类别名称。

以下是类别select * from categories ORDER by ctg_uid ASC;

 ctg_uid |    ctg_category    | ctg_creator_uid 
---------+--------------------+-----------------
       1 | general            |               1
       2 | faults             |               1
       3 | computing          |               1
       4 | teaching           |               2
       5 | QIS-FEEDBACK       |               3
       6 | QIS-PHYS-FEEDBACK  |               3
       7 | SOP-?-CHANGE       |               3
       8 | agenda items       |               7
      10 | Acq & Process      |               2
      12 | physics-jobs       |               3
      13 | Tech meeting items |              12
      16 | incident-forms     |               3
      17 | ERRORS             |               3
      19 | Files              |              10
      21 | QIS-CAR            |               3
      22 | doses              |               4
      24 | admin              |               3
      25 | audit              |               3
      26 | For Sale           |               4
      31 | URGENT-REPORTS     |               4
      34 | dt-jobs            |               3
      35 | JOBS               |               3
      36 | IN-PATIENTS        |               4
      37 | Ordering           |               4
      38 | dep-meetings       |               4
      39 | reporting          |               4

我想要做的是,我们messages上的所有邮件都计算每个类别的频率

我可以按类别进行 SELECT count(msg_ctg_uid) FROM messages where msg_ctg_uid='13';

然而,有可能在一个班轮中这样做吗?

以下给出了每条消息的类别和ctg_uid SELECT ctg_category, msg_ctg_uid FROM messages INNER JOIN categories ON (ctg_uid = msg_ctg_uid);

但是SELECT ctg_category, count(msg_ctg_uid) FROM messages INNER JOIN categories ON (ctg_uid = msg_ctg_uid);

给我错误ERROR: column "categories.ctg_category" must appear in the GROUP BY clause or be used in an aggregate function

如何汇总每个类别的频率?

1 个答案:

答案 0 :(得分:1)

你错过了group by子句:

SELECT ctg_category, count(msg_ctg_uid) 
FROM messages INNER JOIN categories ON (ctg_uid = msg_ctg_uid);
GROUP BY ctg_category

这意味着您需要每ctg_category

的计数