简体   繁体   中英

sql query search for vertical saving

在此输入图像描述

I need to get all the booktypes which has salesyear only in 2013,2014 and should not have sales in any other year. So in my example data, should only return 'nonfiction'.

I have tried

select booktype where salesyear in (2013,2014)

this is returning both fiction and nonfiction, but I need to get the data if the salesyear has only in 2013, 2014 but not in any other year

I am using SQL Server 2008

You can use conditional aggregation:

SELECT booktype
FROM yourTable
GROUP BY booktype
HAVING SUM(CASE WHEN salesyear = 2013 THEN 1 ELSE 0 END) > 0 AND   -- 2013 present
       SUM(CASE WHEN salesyear = 2014 THEN 1 ELSE 0 END) > 0 AND   -- 2014 present
       SUM(CASE WHEN salesyear IN (2013, 2014) THEN 1 ELSE 0 END) = COUNT(*)   -- only 2013 and
                                                                               -- only 2014

You may want to get all BookType with sales in 2013 and 2014, excluding sales in any year other than 2013 / 2014.

SELECT DISTINCT a.BookType
FROM MyTable a 
JOIN MyTable b on a.BookType = b.BookType AND b.SalesYear = 2014
WHERE a.SalesYear = 2013
AND a.BookType NOT IN
(
  SELECT DISTINCT BookType
  FROM MyTable
  WHERE SalesYear NOT IN (2013, 2014)
)

I think this will satisfy your requirement above:

SELECT s.BookType 
FROM Test s
WHERE SalesYear IN (2013,2014)
AND NOT EXISTS(
SELECT BookType 
FROM Test 
WHERE BookType = s.BookType AND SalesYear NOT IN (2013,2014))
GROUP BY BookType HAVING COUNT(DISTINCT(SalesYear)) > 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM