从与另一列中的特定id关联的一列中查找最小值和最大值

时间:2016-09-16 13:40:31

标签: sql sql-server nested

嗨(我对SQl很新),我想找到与id相关联的min和max caseno,并且还能够获得与这些caseno相关的价格。我从两个表中获得的数据如下所示:

表1

Id |Caseno |Price 
-----------------
10 |101    |5
10 |102    |6
10 |103    |7
11 |201    |5
11 |202    |6
12 |203    |5
12 |204    |6
12 |205    |7

表2

Caseno  |Price 
----------------
101     |5
102     |6
103     |7
201     |5
202     |6 
203     |5
204     |6
205     |7

我希望我的输出如下:

Id |Caseno|Price
-----------------
10 |101   | 5
10 |103   | 7
11 |201   | 5
12 |203   | 5
12 |205   | 7

我使用的查询在下面,但它没有给我正确的输出:

select id, price, max(caseno) lowestcaseno ,min(caseno) highestcaseno
from table1 t join table2 a on (t.caseno=a.caseno)
group by id,price

我是否需要创建子查询?如果是的话我应该把它们放在where或where子句中?谢谢,非常感谢任何帮助!

4 个答案:

答案 0 :(得分:0)

您的示例数据存在一些问题,但大多数问题似乎意味着您希望保留每个Id组的最高和最低价格的赌场。如果是这样,那么一种方法是创建一个子查询来识别这些赌场,然后使用这个子查询在原始表中选择正确的完整记录。

SELECT c1.Id,
       c1.Caseno,
       c1.Price
FROM caseno c1
INNER JOIN
(
    SELECT Id,
           MIN(Price) AS minPrice,
           MAX(Price) AS maxPrice
    FROM caseno
    GROUP BY Id
) c2
    ON c1.Id = c2.Id AND
       (c1.Price = c2.minPrice OR
        c1.Price = c2.maxPrice)

答案 1 :(得分:0)

您可以将查询设为

select t1.ID, t1.Caseno, t1.Price from table1 t1
where price = (select min(price) from table1 t2 where t1.Caseno =t2.Caseno )
or price = (select min(price) from table1 t2 where t1.Caseno =t2.Caseno )
order by price

希望你明白了。

答案 2 :(得分:0)

SELECT Id, Caseno, Price, 
       CASE WHEN rn_minPrice = rn_maxPrice THEN 'MIN/MAX'
            WHEN rn_minPrice = 1           THEN 'MIN'
            ELSE 'MAX'
       END result
FROM (
        SELECT Id,
               Caseno,
               Price 
               ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Price )      AS rn_minPrice,
               ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Price DESC ) AS rn_maxPrice,
        FROM table1
     ) as T
WHERE rn_minPrice = 1 or rn_maxPrice = 1

答案 3 :(得分:0)

假设Table1为t1。我不认为表2有任何用作Caseno,价格列也存在于表1中。

;WITH CTE AS
(
   SELECT ID,MIN(PRICE) PRICE FROM T1 GROUP BY ID
   UNION
   SELECT ID,MAX(PRICE) FROM T1 GROUP BY ID
)
SELECT C.ID,T1.CASENO,C.PRICE FROM CTE C 
INNER JOIN T1 ON C.ID=T1.ID AND C.PRICE=T1.PRICE  ORDER BY C.ID