admin管理员组文章数量:1244214
I'm trying to count a book in the database where that belong to different locations.
For example the book "Interview with the Vampire" by Anne Rice exist in both library code of 40 and 30 (two locations).
Book Title Location Number
"Interview with the vampire" 30 (Hudson)
"Interview with the vampire" 40 (Mayfield).
What is the best way to find any book tiles with more than 1 location number.
This is what I have so far, but it's not returning the book tiles with two different location.
select book_title, location_code
from books
group by book_title, location_code
having count(location_code) > 2;
I'm trying to count a book in the database where that belong to different locations.
For example the book "Interview with the Vampire" by Anne Rice exist in both library code of 40 and 30 (two locations).
Book Title Location Number
"Interview with the vampire" 30 (Hudson)
"Interview with the vampire" 40 (Mayfield).
What is the best way to find any book tiles with more than 1 location number.
This is what I have so far, but it's not returning the book tiles with two different location.
select book_title, location_code
from books
group by book_title, location_code
having count(location_code) > 2;
Share
Improve this question
edited yesterday
Yuan
asked Feb 17 at 17:11
YuanYuan
52 bronze badges
5
|
3 Answers
Reset to default 1Assuming your RDBMS supports window functions, you can do a windowed count in a sub-query to determine which books to display, then query their details.
with cte as (
select book_title, location_code,
count(*) over (partition by book_title) BookCount
from books
)
select book_title, location_code
from cte
where BookCount >= 2;
Note: As said in the comments you need >= 2
(or > 1
).
WITH T0 AS (
SELECT DISTINCT book_title, location_code
FROM books
), T1 AS (
SELECT book_title
FROM T0
GROUP BY book_title
HAVING COUNT(*) > 1
)
SELECT T0.*
FROM T0
JOIN T1
ON T0.book_title = T1.book_title;
- First query (T0) to eliminate duplicates row
- Second query to find title that have more than 1 differant location
- Last query to get the result
Converting my comment into answer:
Try this query:
SELECT book_title FROM books GROUP BY book_title HAVING COUNT(DISTINCT location_code) > 1;
Here we group only by book_title
. Later we count the distinct location_codes
using the DISTINCT
keyword.
Playground
本文标签:
版权声明:本文标题:sql - What is the correct way to count a record with two rows with two different values, my having clause is not working - Stack 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740139535a2230627.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
SELECT book_title FROM books GROUP BY book_title HAVING COUNT(DISTINCT location_code) > 1;
, grouping only by book_title and then counting distinct location codes? – Tushar Shahi Commented Feb 17 at 17:18