一个关于统计的SQL问题。

暗黑帝国 2015-02-26 09:26:42
对数据库不是很熟,希望大佬们给个SQL并介绍一下语句。
有3张表 ,分别如下
a表
employeeid name email
001 Tom
002 Jerry

b表
supplierId Name Price
1 圆珠笔 1.00
2 白纸 30.00
3 电池 3.00

c表
employeeid supplierId Numbers
001 2 1
001 1 2
002 1 1
002 3 4

我想得到这样一个统计表
EmployeeName SupplierName Numbers
Tom 白纸 1
Tom 圆珠笔 2
Jerry 圆珠笔 1
Jerry 电池 4

请问怎么写SQL并能适当解释。谢谢!
...全文
161 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
暗黑帝国 2015-02-26
  • 打赏
  • 举报
回复
非常感谢版主的快速响应!
唐诗三百首 2015-02-26
  • 打赏
  • 举报
回复

create table a表
(employeeid varchar(10),name varchar(10),email varchar(20))

insert into a表
 select '001','Tom','' union all
 select '002','Jerry','' union all
 select '003','Cat',''
 
create table b表
(supplierId int,Name varchar(10),Price decimal(8,2))

insert into b表
 select 1,'圆珠笔',1.00 union all
 select 2,'白纸',30.00 union all
 select 3,'电池',3.00

create table c表
(employeeid varchar(10),supplierId int,Numbers int)

insert into c表
 select '001',2,1 union all
 select '001',1,2 union all
 select '002',1,1 union all
 select '002',3,4


select a.name 'EmployeeName',
       b.Name 'SupplierName',
       isnull(c.Numbers,0) 'Numbers'
  from a表 a
  cross join b表 b
 left join c表 c on a.employeeid=c.employeeid and b.supplierId=c.supplierId
 order by a.employeeid
 
/*
EmployeeName SupplierName Numbers
------------ ------------ -----------
Tom          圆珠笔          2
Tom          白纸           1
Tom          电池           0
Jerry        圆珠笔          1
Jerry        白纸           0
Jerry        电池           4
Cat          圆珠笔          0
Cat          白纸           0
Cat          电池           0

(9 row(s) affected)
*/
暗黑帝国 2015-02-26
  • 打赏
  • 举报
回复
多谢版主, 刚才问题描述有些不正确,应该如下: 对数据库不是很熟,希望大佬们给个SQL并介绍一下语句。 有3张表 ,分别如下 a表 employeeid name email 001 Tom 002 Jerry 003 Cat b表 supplierId Name Price 1 圆珠笔 1.00 2 白纸 30.00 3 电池 3.00 c表 employeeid supplierId Numbers 001 2 1 001 1 2 002 1 1 002 3 4 我想得到这样一个统计表 EmployeeName SupplierName Numbers Tom 圆珠笔 2 Tom 白纸 1 Tom 电池 0 Jerry 圆珠笔 0 Jerry 白纸 1 Jerry 电池 4 Cat 圆珠笔 0 Cat 白纸 0 Cat 电池 0 请问怎么写SQL并能适当解释。谢谢!
唐诗三百首 2015-02-26
  • 打赏
  • 举报
回复

select a.name 'EmployeeName',
       b.Name 'SupplierName',
       c.Numbers
 from c表 c
 inner join a表 a on c.employeeid=a.employeeid
 inner join b表 b on c.supplierId=b.supplierId

27,580

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧