Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
juan11041970
Starting Member
2 Posts |
Posted - 2011-08-01 : 16:55:14
|
| The following query:select distinct (a.name), (select count(*) from test.books where author_id = b.author_id) as TOTAL_BOOKS, count(b.numpages) as PROLIFICfrom test.authors a, test.books bwhere a.idauthors = b.author_idand b.year_written >= 1960group by b.numpageshaving b.numpages > 1000Yields the following result:+ --------- + ---------------- + ------------- +| name | TOTAL_BOOKS | PROLIFIC |+ --------- + ---------------- + ------------- +| John Doe | 2 | 1 || Robert Jones | 4 | 2 || Susan Jones | 3 | 1 || Robert Jones | 4 | 1 |+ --------- + ---------------- + ------------- +4 rowsWhat I need is a query that will yield the following result:+ --------- + ---------------- + ------------- +| name | TOTAL_BOOKS | PROLIFIC |+ --------- + ---------------- + ------------- +| John Doe | 2 | 1 || Robert Jones | 4 | 3 || Susan Jones | 3 | 1 |+ --------- + ---------------- + ------------- +3 rowsIf you compare the two results, Robert Jones is included twice in the result.If anybody knows of a way, please let me know.--Thanks |
|
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2011-08-01 : 19:20:02
|
| I'm surprised the query returns anything, as a.name is in your select, but not your group by, and your group by has b.numpages, which will add another row if robert jones is associated with 2 different b.numpages. Are you just trying to count the number of books an author has written since 1960 that have more than 1000 pages?JimEveryday I learn something that somebody else already knew |
 |
|
|
juan11041970
Starting Member
2 Posts |
Posted - 2011-08-01 : 21:59:42
|
| Yes that is what I am trying to do. Total number of books since 1960 and also the total number with more than 1000 pages. In other words, two counts are needed. Total number of books and total number of books with more than 1000 pages.--Thanks |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-08-02 : 00:52:07
|
| [code]select a.name,count(case when b.year_written >= 1960 then 1 else null end) as TOTAL_BOOKS,count(case when b.numpages > 1000 then 1 else null end) as PROLIFICfrom test.authors ajoin test.books bon a.idauthors = b.author_idgroup by a.name[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|
|
|