0

我找不到这个,我敢肯定它很简单。

表(196 行)

tech, name, area, manager
------------------------------
Joe,mary,pa,sally
Kim,brad,ga,tim
kelly,Joe,pa,sally
Joe,jose,pa,sally

一个技术被分配给多个名称/区域/经理。我想做一个报告,显示表格的所有行,其中有一列显示技术分配的数量。

我想要的结果

tech, name, area, manager, (count of number of tech assignments)
Joe,mary,pa,sally,2
Kim,brad,ga,tim,1
kelly,Joe,pa,sally,1
Joe,jose,pa,sally,2
4

4 回答 4

3

我猜你想要一个SELECT子句的子查询:

SELECT 
   name, 
   area, 
   manager, 
   (SELECT COUNT(*) FROM tablename WHERE tech = x.tech) AS assignments
FROM tablename x

这是一种可能更有效的方法来做同样的事情:

SELECT 
   t.name, 
   t.area, 
   t.manager,
    sub.assignments 
FROM tablename t
INNER JOIN (
    SELECT tech, COUNT(*) AS assignments 
    FROM tablename 
    GROUP BY tech
 ) sub
ON sub.tech = t.tech
于 2012-04-18T15:04:29.123 回答
1
select 
    a.tech, a.name, a.area, a.manager,
    b.cnt
from table a, (
    select count(*) cnt, tech
    from table
    group by tech) b
where a.tech=b.tech;

这是你想要的吗?

于 2012-04-18T15:11:20.073 回答
0
SELECT tech, count(name) AS total_records FROM db_table GROUP BY tech

不确定这是您要查找的内容。哦,是的,看起来你真的需要使用子查询。感谢您的示例,这有帮助。

于 2012-04-18T15:12:21.070 回答
0
SELECT tech, name, area, manager, assignments  
FROM table
  INNER JOIN ( 
    SELECT tech, COUNT(*) AS assignments  
    FROM table  
    GROUP BY tech 
  ) t 
USING (tech)

解释:

从表中选择所有列,并将它们与包含技术列的表和具有特定技术的表中的行数连接起来。关键字 USING 表示这两个表如何合并。

于 2012-04-18T15:21:01.793 回答