SQL count() over 2 tables by a type

巧了我就是萌 提交于 2019-12-13 07:45:33

问题


I have a question how to make the right sql statement, because I have no Idea how to start ;-(

There are the following two tables:

Table 1: test

id|name|type
-------------
1|FirstUnit|1
2|FirstWeb|2
3|SecondUnit|1

Table 2: types

id|type
--------
1|UnitTest
2|WebTest

I would like to get the following result:

Table result:

type|amount
-----------
UnitTest|2
WebTest|1

Can anyone helping with giving a hint how to start?

Thanks in advance. LStrike


回答1:


You can try this query:

SELECT
    t.type ,
    COUNT(*) AS amount
FROM types AS t
   JOIN test AS te ON t.id= te.type
GROUP BY type
ORDER BY t.type



回答2:


SELECT  a.type, COUNT(b.type) amount
FROM    types a
        LEFT JOIN test b
            ON a.ID = b.type
GROUP   BY a.type
ORDER   BY amount DESC
  • SQLFiddle Demo

To further gain more knowledge about joins, kindly visit the link below:

  • Visual Representation of SQL Joins



回答3:


Here is the solution:-

 SELECT  types.type, COUNT(test.type) as amount from types,test where test.type=types.id 
 GROUP BY test.type
 ORDER BY amount


来源:https://stackoverflow.com/questions/15807635/sql-count-over-2-tables-by-a-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!