如何将这两列连接为一个查询?

wkftcu5l  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(280)

我想在姓名表中找出重复姓名的数量。就像

names       
------
jhon
jhon
jack
jhon
jack

我做了下面的查询来统计这些名字的出现次数

select count(names) as namejhon from table_team where names=‘jhon’  
select count(names) as namejack from table_team where names=‘jack’

由此,我想得到下表(期望的结果)

namejhon       namejack
----------- -----------
         3          2

  1 record(s) selected.

但是当我使用join时

namejack       
----------- 
         5        

  1 record(s) selected.

我该怎么做才能得到想要的结果?感谢您的指导。

ecfsfe2w

ecfsfe2w1#

下面的代码将为您提供所需的信息,但它是一个查询,而不是一个表。如果确实要创建一个列/字段名为人名、行/记录仅为计数的表,则应查看create table文档:https://dev.mysql.com/doc/refman/5.5/en/creating-tables.html 以及插入命令文档:https://dev.mysql.com/doc/refman/8.0/en/insert.html.

SELECT
    COUNT(names) AS COUNT,
    names
FROM
    table_team
WHERE
    names in ('jhon', 'jack')
GROUP BY
    names

在原始海报的新信息后添加:

SELECT
    *
FROM
    (SELECT COUNT(*) AS nameJack FROM table_team WHERE `names` = 'jack') AS SUB1
INNER JOIN
    (SELECT COUNT(*) AS nameJhon FROM table_team WHERE `names` = 'jhon') AS SUB2
    ON
    (
    SUB1.`nameJack` <> SUB2.`nameJhon`
    OR
    SUB1.`nameJack` = SUB2.`nameJhon`
     )
icomxhvb

icomxhvb2#

对于mysql:
使用两个子选项。

SELECT (SELECT count(names)
               FROM table_team
               WHERE names = 'jhon') namejhon,
       (SELECT count(names)
               FROM table_team
               WHERE names = 'jack') namejack;

如果你想实现这一点,使用 CREATE TABLE ... AS SELECT ... 斯奈塔克斯。

CREATE TABLE jhon_and_jack
AS
SELECT (SELECT count(names)
               FROM table_team
               WHERE names = 'jhon') namejhon,
       (SELECT count(names)
               FROM table_team
               WHERE names = 'jack') namejack;

但是我不知道db2。但这也会给你一些提示。

相关问题