作者hhomerun (HOMERUN家族弟弟)
看板Database
标题Re: [SQL ] 数量统计问题?
时间Fri Jul 11 19:27:25 2014
Hello,
SELECT [a].[name]
,case when SUM([station].[qty]) IS NULL then 0
else SUM([station].[qty]) end [qty]
FROM (SELECT distinct [name] FROM [test].[dbo].[a]) AS [a]
LEFT JOIN [test].[dbo].[station2] AS [station]
ON [a].[name]=[station].[name]
GROUP BY [a].[name]
这样应该就会有你想要的样子,
case when 那边是因为 如果没任何某个name的资料它会显示出NULL
你好像想要它显示0 所以就用一个条件式让它显示0
然後想要看station1 的时候
就把 LEFT JOIN的那行 [station2] 改成 [station1] 就好了
祝福你工作或是专案顺利搂~~~~
※ 引述《joedenkidd (优质的蓝色射手)》之铭言:
: Dear All
: A Table(a)
: name station
: A station1
: A station2
: B station1
: C station1
: B Table (station1)
: name qty
: A 10
: B 20
: select count(*) from station1 group by name
: 结果:
: A 10
: B 20
: 但是
: select distinct a.name,count(station1.*) from a left join station on a.name=station.name group by a.name
: 结果
: A 20
: B 20
: 看来是因为 a table name=A 出现两次
: 如果说用
: select distinct a.name,count(station1.*) from a left join station on a.name=station.name where a.name='station1' group by a.name
: A 10--->数量是对的
: B 20
: 但我希望做到的是
: 1 从a table 找出所有不重复的 name
: 2 再用a.name到 station1.....station2 不同table做统计
: 在station1中
: A 10
: B 0
: C 20
: 在station2中
: A 0
: B 10
: C 10
: 而不是
: station1
: A 10
: C 20
: station2
: B 10
: C 10
: 麻烦大家帮忙解惑,谢谢
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 111.248.237.58
※ 文章网址: http://webptt.com/cn.aspx?n=bbs/Database/M.1405078049.A.519.html
※ 编辑: hhomerun (111.248.237.58), 07/11/2014 19:45:28
1F:推 joedenkidd:感谢~~我再试看看!! 07/11 21:17