对表中的重复列求和

时间:2012-03-14 22:44:52

标签: sql database sql-server-2008

我正在使用发布商数据库,我正在查询列出在任何书店销售的书籍的名称和数量,以便在Bookbeat商店销售任何书籍的每位作者。

当我执行此查询时

SELECT DISTINCT au_lname, au_fname, qty
from authors
JOIN titleauthor on titleauthor.au_id = authors.au_id
JOIN titles on titles.title_id = titleauthor.title_id
JOIN sales on sales.title_id = titles.title_id
JOIN stores on stores.stor_id = sales.stor_id
--WHERE stor_name LIKE 'Bookbeat' 

我得到了这个结果

Bennet  Abraham 5
Bennet  Abraham 10
Blotchet-Halls  Reginald    20
Carson  Cheryl  30
DeFrance    Michel  15
DeFrance    Michel  25
del Castillo    Innes   10
Dull    Ann 50
Green   Marjorie    5
Green   Marjorie    10
Green   Marjorie    35
Gringlesby  Burt    20
Hunter  Sheryl  50
Karsen  Livia   20
Locksley    Charlene    25
MacFeather  Stearns 20
MacFeather  Stearns 25
O'Leary Michael 20
O'Leary Michael 25
Panteley    Sylvia  40
Ringer  Albert  3
Ringer  Albert  10
Ringer  Albert  20
Ringer  Albert  25
Ringer  Albert  75
Ringer  Anne    3
Ringer  Anne    10
Ringer  Anne    15
Ringer  Anne    20
Ringer  Anne    25
Ringer  Anne    75
Straight    Dean    15
White   Johnson 15
Yokomoto    Akiko   20

但是当我取消注释我得到的地方时

Bennet  Abraham 10
Carson  Cheryl  30
DeFrance    Michel  15
Green   Marjorie    10
MacFeather  Stearns 25
O'Leary Michael 25
Ringer  Anne    15

我认为我要找的是将重复数字加起来以便得到正确的答案。 所以Bennet Abraham的实际数量是15。

1 个答案:

答案 0 :(得分:2)

这是一种方式(您应该始终在GROUP BY中包含PK,因为作者姓名不能保证唯一)

SELECT au_lname, 
       au_fname, 
       SUM(qty) AS qty 
FROM   authors 
       JOIN titleauthor 
         ON titleauthor.au_id = authors.au_id 
       JOIN titles 
         ON titles.title_id = titleauthor.title_id 
       JOIN sales 
         ON sales.title_id = titles.title_id 
       JOIN stores 
         ON stores.stor_id = sales.stor_id 
GROUP  BY  authors.au_id,
           au_lname, 
           au_fname 
HAVING MAX(CASE 
             WHEN stor_name = 'Bookbeat' THEN 1 
           END) = 1 

或者另一个避免对不符合条件的作者求助但两次加入。

;WITH CTE As
(
SELECT     authors.au_id,
           au_lname, 
           au_fname,
           stor_name,
           qty          
FROM   authors 
       JOIN titleauthor 
         ON titleauthor.au_id = authors.au_id 
       JOIN titles 
         ON titles.title_id = titleauthor.title_id 
       JOIN sales 
         ON sales.title_id = titles.title_id 
       JOIN stores 
         ON stores.stor_id = sales.stor_id 
)
SELECT au_lname, 
       au_fname, 
       SUM(qty) AS qty 
FROM   CTE 
WHERE au_id IN (SELECT au_id FROM CTE WHERE stor_name = 'Bookbeat')
GROUP  BY  au_id,
           au_lname, 
           au_fname