Re: [SQL ] 數量統計問題?
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://www.ptt.cc/bbs/Database/M.1405078049.A.519.html
※ 編輯: hhomerun (111.248.237.58), 07/11/2014 19:45:28
推
07/11 21:17, , 1F
07/11 21:17, 1F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):