无法使用行号和分组依据检索具有最高值列的行

时间:2014-08-11 15:12:06

标签: sql sql-server

我正在处理一个查询,该查询返回每行产品价格最高的一行。

例如我有

表T1

Product Price Tax   Location
Pen     10    2.25  A
Pen      5    1.25  B
Pen     15    1.5   A 
Board   25    5.26  A
Board    2    NULL  B
Water    5    10    A

结果应该像

Product Price Tax   Location       
 Pen     15    1.5   A 
 Board   25    5.26  A
 Water    5    10    A

我正在使用row number()group by来使用以下

来实现此目的
ALTER VIEW [dbo].[InferredBestBids]
AS
    SELECT  ROW_NUMBER() OVER ( ORDER BY ( SELECT   NULL
                                         ) ) AS id ,
            product ,
            MAX(price) AS Price ,
            MIN(tax) AS Tax ,
            location
    FROM    [dbo].InferredBids_A
    WHERE   NOT ( proce IS NULL
                  AND tax IS NULL
                )
    GROUP BY market ,
            term
GO

当我运行上述查询时,它向我提出了错误

Column 'dbo.InferredBids_A.Location' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

当我尝试按location对查询结果进行分组时,根据product

location返回多行,这给了我错误的结果

4 个答案:

答案 0 :(得分:1)

如果你正确地使用了row_number子句,然后根据rownumber选择,则不需要GROUP BY。如果由于其他原因需要,可以随意在外部查询的前面添加额外的row_number调用。 See the example here

SELECT Product, Price, Tax, Location
FROM (
  SELECT Product, Price, Tax, Location, ROW_NUMBER()OVER(PARTITION BY Product ORDER BY Price DESC) as RowID
  FROM InferredBids_A
  ) T
WHERE RowID = 1

答案 1 :(得分:1)

如果您选择了汇总的内容,则必须GROUP BY选择列表中尚未汇总的任何内容:

SELECT Product, Price ,Tax, Location
FROM (SELECT Product, Price ,Tax, Location, 
    RANK() OVER (PARTITION BY Product ORDER BY Price DESC) N
    FROM InferredBids_A
    WHERE Price IS NOT NULL AND Tax IS NOT NULL
) T WHERE N = 1

RANK会为关系提供行,如果您不关心这些,请使用ROW_NUMBER

答案 2 :(得分:1)

制作一些测试数据:

DECLARE @BestBids TABLE
(
    Product VARCHAR(20),
    Price INT, 
    Tax DECIMAL(10,2),
    Location VARCHAR(10)
)

INSERT INTO @BestBids
VALUES
('Pen', 10, 2.25, 'A'),
('Pen', 5, 1.25,  'B'),
('Pen', 15, 1.5,   'A'), 
('Board', 25, 5.26,  'A'),
('Board', 2, NULL,  'B'),
('Water', 5, 10,   'A');

我们将行号设置为每种产品的最高价格。

SELECT * FROM
(
    SELECT *,
        ROW_NUMBER() OVER (PARTITION BY Product ORDER BY Price DESC) RN
    FROM @BestBids
) a
WHERE RN=1

我们包装sql并只选择第一行号。这是输出:

Product Price   Tax     Location    RN
Board   25      5.26    A           1
Pen     15      1.50    A           1
Water   5       10.00   A           1

答案 3 :(得分:0)

您可以使用公用表表达式:

WITH    cte
          AS ( SELECT   product ,
                        MAX(price) AS price
               FROM     dbo.InferredBids_A
             )
    SELECT  product ,
            price ,
            tax ,
            location
    FROM    dbo.InferredBids_A tbl
            INNER JOIN cte ON cte.product = tbl.product
                              AND cte.price = tbl.price