2

こんな感じでユニオンやってます

select name, price from products where project = 10  // prio 1
union
select name, price from products where customer = 5  // prio 2
union
select name, price from products where standard = 9  // prio 3

編集:where句を変更して、もう少し複雑にしました

これは通常、私に返してくれます

+-----+------+-----------+--------------+
|(NO) | name |  price    |  (prio)      |
+-----+------+-----------+--------------+
|  1  |  a   |    10     |  (1)         |
|  2  |  b   |     5     |  (1)         |

|  3  |  a   |    13     |  (2)         |
|  4  |  b   |     2     |  (2)         |

|  5  |  a   |     1     |  (3)         |
|  6  |  b   |     5     |  (3)         |
|  7  |  c   |     3     |  (3)         |
+-----+------+-----------+--------------+

たとえば、行番号 1 と 3 は重複しておらず、union ステートメントによって削除されないことを理解しています。しかし、これはまさに私がやりたいことです。つまり、名前 (例: "a") が最初の select ステートメント (prio 1) によって返された場合、他の "a":s が優先度の高い select ステートメントから結果セットに入らないようにします。

つまり、これが欲しい:

+-----+------+-----------+--------------+
|(NO) | name |  price    |  (prio) |
+-----+------+-----------+--------------+
|  1  |  a   |    10     |  (1)         |
|  2  |  b   |     5     |  (1)         |

|  7  |  c   |     3     |  (3)         |
+-----+------+-----------+--------------+

これは可能ですか?

使用してみgroup byましたが、これには、やりたくない価格でMIN、MAX、AVGなどを使用する必要があります。

select name, avg(price) from (...original query...) group by name
// this is not ok since I donnot want the avg price, I want the "first" price

MS SQL 2000 を使用first(..)していgroup byます。これを試すと、エラーが発生します。

select name, first(price) from (...original query...) group by name
// error: 'first' is not a recognized built-in function name.

ありがとう!

4

3 に答える 3

2

SQL Server 2005 以降の場合:

WITH records
AS
(
    SELECT  name, price, prio,
            ROW_NUMBER() OVER (PARTITION BY name
                                ORDER BY prio ASC) rn
    FROM    products
)
SELECT  Name, Price
FROM    records
WHERE   rn = 1

これを試してくださいSQL Server 2000

SELECT  a.*
FROM    products a
        INNER JOIN
        (
            SELECT  name, MIN(prio) min_prio
            FROM    products 
            WHERE   prio IN (1,2,3)
            GROUP   BY  name
        ) b ON a.name = b.name AND
                a.prio = b.min_prio

パフォーマンスを向上させるには、列に複合インデックスを追加します(name, prio)

于 2013-03-04T09:37:03.317 に答える
1

それが機能するかどうかはわかりませんが、アイデアは次のとおりです。

select name,
    min(case when prio=min_prio then price else NULL end) as price,
    min(prio) as min_prio
from products
group by name
order by min_prio
于 2013-03-04T09:55:58.393 に答える
1
select name, price from products where prio = 1
union
select name, price from products where prio = 2 and name not in (select name from products where prio = 1)

union
select name, price from products where prio = 3 and name not in 
(select name from products where prio = 1
union
select name from products where prio = 2 and name not in (select name from products where prio = 1))
于 2013-03-04T09:36:33.923 に答える