通过cartain关联的行值按顺序返回结果

时间:2017-06-20 17:43:46

标签: sql sql-server

我有一个查询可以撤回一些数据。

    SELECT *
    FROM [contract_attr]
    WHERE item_id IN (
            SELECT item_id
            FROM contract_attr
            WHERE field_id = 234
                AND attr_val IN (
                    SELECT attr_val
                    FROM contract_attr
                    WHERE field_id = 234
                        AND attr_val IN (
                            SELECT item_pk
                            FROM mfr
                            WHERE item_id = 13
                            )
                    ) 
            )

enter image description here

查看field_id为413的行。我需要item_ids的顺序按字母顺序排列,其中field_id = 413的行的attr_val是按顺序排列的。我希望这是有道理的。

我做了一个查询:

SELECT item_id
FROM [contract_attr]
WHERE field_id = 413
    AND item_id IN (
        SELECT item_id
        FROM [contract_attr]
        WHERE attr_val = (
                SELECT item_pk
                FROM mfr
                WHERE item_id = 13
                )
        )
ORDER BY attr_val

enter image description here

但是当我将它添加到查询中时:

SELECT *
FROM [contract_attr]
WHERE item_id IN (
        SELECT item_id
        FROM [contract_attr]
        WHERE field_id = 413
            AND item_id IN (
                SELECT item_id
                FROM [contract_attr]
                WHERE attr_val = (
                        SELECT item_pk
                        FROM mfr
                        WHERE item_id = 13
                        )
                )
        ORDER BY attr_val
        )

我得到The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

我该如何解决这个问题?我在这里看到(The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions)我不能通过内部查询使用顺序,但是我如何获得所需的结果呢?

2 个答案:

答案 0 :(得分:3)

所有嵌套查询都可以转换为join和where子句。从我所能说的一遍又一遍地查询同一张表,没有任何意义。

SELECT 
    a.*
 FROM 
    [contract_attr] a
 INNER JOIN 
     mfr r on 
     r.item_pk = a.attr_val
 WHERE 
    a.field_id = 234 
    and r.item_id = 13
ORDER BY a.attr_val

答案 1 :(得分:1)

您可以使用order by

中的窗口函数在最外层执行此操作
order by max(case when field_id = 413 then attr_val end) over (partition by item_id)