sql table的count()函数

时间:2015-06-11 15:01:20

标签: sql sql-server

如何将名称计为总数

表1是

PROGRAM, PART,COLOR 

表2是

SERIAL,NAME

查询:

select program,table_1.part_customer,color, table_2.[serial],table_2.operator
from table_1 
inner join table_2 
on Table_1.[PART_customer]=table_2.[PART_customer_1]

OUTPUT如下所示;

PROGRAM     PART    COLOR     SERIAL    NAME              
-------     ----    -----      ----     -----
BMW          100    BLUE      1         STEVE
BMW          100    BLUE      1         STEVE
BMW          100    BLUE      1         STEVE
MERCEDES     200    SILVER    2         NEIL
MERCEDES     200    SILVER    2         NEIL
AUDI         300    GREEN     3         JOHN
AUDI         300    GREEN     3         JOHN  
MERCEDES     200    SILVER    2         NEIL
MERCEDES     200    SILVER    3         NEIL
BMW          100    BLUE      1         STEVE
BMW          100    BLUE      1         STEVE
GM           500    RED       5         MIKE
GM           500    RED       5         MIKE
GM           500    RED       5         MIKE
VOLKSWAGEN   400    BLACK     4         DAVID
VOLKSWAGEN   400    BLACK     4         DAVID
VOLKSWAGEN   400    BLACK     4         DAVID
VOLKSWAGEN   400    BLACK     4         DAVID
VOLKSWAGEN   400    BLACK     4         DAVID

我希望输出为

PROGRAM     PART    COLOR     SERIAL    NAME      TOTAL          
-------     ----    -----      ----     -----     -----
BMW         100    BLUE       1        STEVE      5
MERCEDES    200    SILVER     2        NEIL       4
AUDI        300    GREEN      3        JOHN       2
GM          500    RED        5        MIKE       3
VOLKSWAGEN  400    BLACK      4        DAVID      5

1 个答案:

答案 0 :(得分:1)

这是你要找的吗?

select program,table_1.part_customer,color, 
    table_2.[serial],table_2.operator, count(*) as total
from table_1 
inner join table_2 
on Table_1.[PART_customer]=table_2.[PART_customer_1]
group by program,table_1.part_customer,color, table_2.[serial],table_2.operator

您应该对表使用表别名,并对查询中的所有列使用该别名,否则如果有人在查询的其中一个表中添加了具有相同名称的列,则SQL可能会中断。