简体   繁体   中英

MSSQL - OVER, ROW_NUMBER() and ORDER BY error

I'm trying to make a query that outputs a list with the company data and the number of Products and Discounts of each Company and order by product_count. Also i need to limit the output to groups of 30 rows

SELECT * FROM (
    SELECT *, (
        SELECT COUNT(*) FROM Products WHERE Product_Comp_id = Comp_id
    ) as product_count, (
        SELECT COUNT(*) FROM Discount WHERE Disc_Comp_id = Comp_id
    ) as discount_count , ROW_NUMBER() OVER (
        ORDER BY product_count ASC
    ) AS RowNum FROM Company
) AS finalTable WHERE finalTable.RowNum BETWEEN 0 AND 30

But i get this error

Invalid column name 'product_count'.

Table Structure

Products
    |-Product_id
    |-Product_Name
    |-Product_Description
    |-Product_Comp_id

Discount
    |-Disc_id
    |-Disc_Name
    |-Disc_Comp_id
    |-Disc_Ammount

Company
    |-Comp_id
    |-Comp_Name
    |-Comp_Address

You need an additional level of subquery to give you product_count.

SELECT * FROM (
    SELECT * , ROW_NUMBER() OVER (ORDER BY product_count ASC) AS RowNum
    FROM 
    (
        SELECT *, (SELECT COUNT(*) FROM Products WHERE Product_Comp_id = Comp_id) as product_count, 
        (SELECT COUNT(*) FROM Discount WHERE Disc_Comp_id = Comp_id) as discount_count
        FROM Company
    ) C
) AS finalTable WHERE finalTable.RowNum BETWEEN 0 AND 30

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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