SQL从选择查询中选择

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL从选择查询中选择相关的知识,希望对你有一定的参考价值。

我想执行一个执行第一个选择的选择请求,然后使用该选择执行第二个选择。

我使用临时表创建了第一个版本,但我想知道是否有办法在没有临时表的情况下执行此操作

我的临时表代码如下:

select  dvd_name, book_name  , count(*) nb
into #t
from usr 
inner join book on usr_book_id  = book_id 
inner join dvd on dvd_id = usr_dvd_id
group by dvd_name, book_name 
having count(*) > 1

select  top 10 usr_smthg,  #t.book_name,dvd_name
from #t
inner join book b on b.book_name = #t.book_name
inner join usr on usr_book_id  = book_id 
答案

您可以使用CTE

with t as
(
    select  dvd_name, book_name  , count(*) nb
    from usr 
    inner join book on usr_book_id  = book_id 
    inner join dvd on dvd_id = usr_dvd_id
    group by dvd_name, book_name 
    having count(*) > 1
)

select  top 10 usr_smthg,  t.book_name,dvd_name
from t
inner join book b on b.book_name = t.book_name
inner join usr on usr_book_id  = book_id 
另一答案

在sql中,您可以使用子查询,如下所示:

select  top 10 usr.usr_smthg,  t.book_name, usr.dvd_name
from (
  select  dvd_name, book_name  , count(*) nb
  from usr 
  inner join book on usr_book_id  = book_id 
  inner join dvd on dvd_id = usr_dvd_id
  group by dvd_name, book_name 
  having count(*) > 1
) t
inner join book b on b.book_name = t.book_name
inner join usr on usr_book_id  = book_id 
-- guess
order by n.nb desc
另一答案

您可以使用带子查询的窗口函数:

select top (10) t.usr_smthg, t.book_name, t.dvd_name
from (select usr_smthg, book_name, dvd_name, 
             count(*) over (partition by dvd_name, book_name) as cnt
      from usr inner join 
           book 
           on usr_book_id  = book_id inner join 
           dvd 
           on dvd_id = usr_dvd_id
     ) t
 where cnt > 1 
 order by ??;

??表示根据您想要的top (10)记录订购列。

以上是关于SQL从选择查询中选择的主要内容,如果未能解决你的问题,请参考以下文章

Sql查询从数据中选择第三个元素? [复制]

如何从 Pentaho-Kettle 中基于动态选择的 sql 查询中获取结果集?

SQL查询返回从数组中选择作者的数据[重复]

进行从多列中选择值列表的 SQL 查询

从 SQL 选择查询创建 XML

从日期中选择特定记录的 SQL 查询