我有以下表结构:
+----------+---------+
| Trade |
+----------+---------+
| Trade_Id | Book_Id |
+----------+---------+
+---------+-----------+
| Book |
+---------+-----------+
| Book_Id | Book_Name |
+---------+-----------+
+----------+--------------+---------------+
| Keyword |
+----------+--------------+---------------+
| Trade_Id | Keyword_Name | Keyword_Value |
+----------+--------------+---------------+
现在我想从具有一个特定重复关键字的特定图书中检索交易。我有一个查询工作,但我讨厌它,因为我基本上重复where子句中的wohle查询。
select
t.TRADE_ID,
kw.KEYWORD_VALUE
from
trade t
inner join book b on b.BOOK_ID = t.BOOK_ID
and b.BOOK_NAME = 'test123'
inner join TRADE_KEYWORD kw on kw.TRADE_ID = t.TRADE_ID
and kw.KEYWORD_NAME = 'ISIN'
where
kw.KEYWORD_VALUE in (
select
kw2.KEYWORD_VALUE
from
trade t2
inner join book b2 on b2.BOOK_ID = t2.BOOK_ID
and b2.BOOK_NAME = 'test123'
inner join TRADE_KEYWORD kw2 on kw2.TRADE_ID = t2.TRADE_ID
and kw2.KEYWORD_NAME = 'ISIN'
group by kw2.KEYWORD_VALUE
having count (*) > 1)
我怎样才能更优雅地做到这一点? 谢谢!
答案 0 :(得分:1)
select TRADE_ID, KEYWORD_VALUE from
(select
t.TRADE_ID,
kw.KEYWORD_VALUE,
count(kw.KEYWORD_VALUE) over(partition by kw.KEYWORD_VALUE) n
from
trade t
inner join book b on b.BOOK_ID = t.BOOK_ID
and b.BOOK_NAME = 'test123'
inner join TRADE_KEYWORD kw on kw.TRADE_ID = t.TRADE_ID
and kw.KEYWORD_NAME = 'ISIN'
)
where n > 1;
您可以使用分析功能。它们与聚合函数类似,但为每一行提供结果(PARTITION BY类似于GROUP BY)。