首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

sql相同名称记录数量求和?该如何处理

2012-06-14 
sql相同名称记录数量求和?急work_pz_sj 表如下idche_cx1奥迪2奥迪3宝马4奔驰sm_peijcx 表如下idchex_mc1奔

sql相同名称记录数量求和?急
work_pz_sj 表如下

id che_cx
1 奥迪
2 奥迪
3 宝马
4 奔驰

sm_peijcx 表如下
id chex_mc
1 奔驰
2 奥迪
3 宝马


我想要通过两个表对比求总和如下效果: 

车型 数量 
奥迪 2  
宝马 1 
奔驰 1  

我现在的查询语句 是
select w.che_cx,s.chex_mc from work_pz_sj AS W,sm_peijcx AS S WHERE w.che_cx=s.chex_mc

通过两个表的对比 得出 所有相同车型 但是现在的数据 没有个总和


请各位大虾帮忙解决!!



[解决办法]

SQL code
漏了2个别名:select a.fn,fc1,fc2from (select che_cx fn,count(*) fc1from work_pz_sj group by che_cx) ajoin (select chex_mc fn,count(*) fc2from sm_peijcx group by chex_mc) b on a.fn=b.fn
[解决办法]
SQL code
------------------------------ Author  :fredrickhu(小F,向高手学习)-- Date    :2012-06-12 09:30:52-- Version:--      Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86) --    Apr 22 2011 11:57:00 --    Copyright (c) Microsoft Corporation--    Enterprise Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64)--------------------------------> 测试数据:[work_pz_sj]if object_id('[work_pz_sj]') is not null drop table [work_pz_sj]go create table [work_pz_sj]([id] int,[che_cx] varchar(4))insert [work_pz_sj]select 1,'奥迪' union allselect 2,'奥迪' union allselect 3,'宝马' union allselect 4,'奔驰'--> 测试数据:[sm_peijcx]if object_id('[sm_peijcx]') is not null drop table [sm_peijcx]go create table [sm_peijcx]([id] int,[chex_mc] varchar(4))insert [sm_peijcx]select 1,'奔驰' union allselect 2,'奥迪' union allselect 3,'宝马'--------------开始查询--------------------------select  a.che_cx as 车型,count(a.che_cx) as 数量from   work_pz_sj a join sm_peijcx bon  a.che_cx=b.chex_mcgroup by   a.che_cx----------------结果----------------------------/* 车型   数量---- -----------奥迪   2宝马   1奔驰   1(3 行受影响)*/ 

热点排行
Bad Request.