2012-03-14 62 views
2

我使用的是发布商数据库,我正在查询以列出在任何书店出售的书籍的名称和数量,以供每位在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 

我想我在寻找什么因为是将复制品加起来以便我得到正确的答案。 所以班纳特亚伯拉罕的实际数量将是15

回答

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 
+0

最佳方法 - 通过删除HAVING子句并在GROUP BY子句之前插入WHERE stor_name ='Bookbeat''来修改1st语句。 – dbenham 2012-03-15 00:58:10

+1

@dbenham - 这不会返回所需的结果。他们希望所有书籍的计数(在任何商店出售),但只限于在Bookbeat商店出售书籍的作者。 – 2012-03-15 09:08:19

+0

该死的,我需要仔细阅读。 – dbenham 2012-03-16 00:48:53