简体   繁体   English

如何在一个查询中返回顶行和底行?

[英]How to return top and bottom row in one query?

I am trying to write a query that will produce the top row and bottom row in one query. 我正在尝试编写一个查询,该查询将在一个查询中产生第一行和最后一行。 I can find one or the other but I cant get both in one row. 我可以找到一个或另一个,但我不能同时获得两者。

Here is what I have: 这是我所拥有的:

SELECT (SELECT top(1) Lastname + ',' + firstname FROM
CUSTOMERS 
     join orders on customerID = customerID_fk 
     join orderDetails on orderID = orderID_fk
group by Lastname + ',' + firstname
order by sum(quantity) desc);

Here is a link: http://sqlfiddle.com/#!6/51ad4/129 这是链接: http : //sqlfiddle.com/#!6/51ad4/129

What is the best practice to get the return I am looking for? 获得我想要的回报的最佳实践是什么?

Here is one way using window functions: 这是使用窗口函数的一种方法:

select name
from (SELECT Lastname + ',' + firstname as name,
             row_number() over (order by sum(quantity)) as rownum,
             count(*) over () as cnt
      FROM CUSTOMERS 
           join orders on customerID = customerID_fk 
           join orderDetails on orderID = orderID_fk
      group by Lastname + ',' + firstname
     ) t
where rownum = 1 or rownum = cnt;

Here is another way: 这是另一种方式:

with cte as (
      SELECT Lastname + ',' + firstname as name, sum(quantity) as qty
      FROM CUSTOMERS 
           join orders on customerID = customerID_fk 
           join orderDetails on orderID = orderID_fk
      group by Lastname + ',' + firstname
)
select top 1 name from cte order by qty union all
select top 1 name from cte order by qty desc;

I think you are looking for Union 我想你在找联盟

SELECT top(1) Lastname + ',' + firstname FROM
CUSTOMERS 
     join orders on customerID = customerID_fk 
     join orderDetails on orderID = orderID_fk
group by Lastname + ',' + firstname
order by sum(quantity) desc Union
SELECT top(1) Lastname + ',' + firstname FROM
CUSTOMERS 
     join orders on customerID = customerID_fk 
     join orderDetails on orderID = orderID_fk
group by Lastname + ',' + firstname
order by sum(quantity) asc

Possibly we can use sub query for this. 可能我们可以为此使用子查询。 The idea is to find out the Max and Minimum ordered items. 这个想法是找出最大和最小订购数量。 Then we can use existing query and write something like sum(quantity) in (Sub Query Here). 然后,我们可以使用现有查询并在(此处的子查询)中编写诸如sum(quantity)之类的内容。

Or can you check if the following works? 还是可以检查以下项目是否有效?

SELECT (SELECT Top(2) Lastname + ',' + firstname FROM
CUSTOMERS 
     join orders on customerID = customerID_fk 
     join orderDetails on orderID = orderID_fk
group by Lastname + ',' + firstname
order by sum(quantity) desc having sum(quantity) = 
Max(Sum(quantity)) or Sum(quantity)=Min(Sum(Quantity))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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