查询中的Count和Avg以确定结果是否大于x

时间:2015-03-18 13:30:15

标签: sql

我抓住机会学习sql。我有一个名为book的基本表。我已经看到了这个场景:显示书籍类别和数量 平均价格大于15的书籍的每本书类别的书籍 美元。我的查询无效。我如何计算每本书type并获得平均价格以查看它是否大于15?

查询

SELECT type FROM books WHERE COUNT(DISTINCT type) * SUM(price) > 15;

表架构

Select * From Book;

BOOK TITLE                                    PUB TYP      PRICE P
---- ---------------------------------------- --- --- ---------- -
0180 A Deepness in the Sky                    TB  SFI       7.19 Y
0189 Magic Terror                             FA  HOR       7.99 Y
0200 The Stranger                             VB  FIC          8 Y
0378 Venice                                   SS  ART       24.5 N
079X Second Wind                              PU  MYS      24.95 N
0808 The Edge                                 JP  MYS       6.99 Y
1351 Dreamcatcher: A Novel                    SC  HOR       19.6 N
1382 Treasure Chests                          TA  ART      24.46 N
138X Beloved                                  PL  FIC      12.95 Y
2226 Harry Potter and the Prisoner of Azkaban ST  SFI      13.96 N
2281 Van Gogh and Gauguin                     WP  ART         21 N
2766 Of Mice and Men                          PE  FIC       6.95 Y
2908 Electric Light                           FS  POE         14 N
3350 Group: Six People in Search of a Life    BP  PSY       10.4 Y
3743 Nine Stories                             LB  FIC       5.99 Y
3906 The Soul of a New Machine                BY  SCI      11.16 Y
5163 Travels with Charley                     PE  TRA       7.95 Y
5790 Catch-22                                 SC  FIC         12 Y
6128 Jazz                                     PL  FIC      12.95 Y
6328 Band of Brothers                         TO  HIS        9.6 Y
669X A Guide to SQL                           CT  CMP      37.95 Y
6908 Franny and Zooey                         LB  FIC       5.99 Y
7405 East of Eden                             PE  FIC      12.95 Y
7443 Harry Potter and the Goblet of Fire      ST  SFI      18.16 N
7559 The Fall                                 VB  FIC          8 Y
8092 Godel, Escher, Bach                      BA  PHI         14 Y
8720 When Rabbit Howls                        JP  PSY       6.29 Y
9611 Black House                              RH  HOR      18.81 N
9627 Song of Solomon                          PL  FIC         14 Y
9701 The Grapes of Wrath                      PE  FIC         13 Y
9882 Slay Ride                                JP  MYS       6.99 Y
9883 The Catcher in the Rye                   LB  FIC       5.99 Y
9931 To Kill a Mockingbird                    HC  FIC         18 N

1 个答案:

答案 0 :(得分:0)

如果要在过滤器中包含聚合,则应GROUP BY,然后使用HAVING子句。

SELECT type FROM books 
GROUP BY type
HAVING COUNT(*) * SUM(price) > 15;