为另一列的每个唯一值选择具有一个列的唯一值的行

时间:2019-02-06 22:32:17

标签: sql sql-server

输入:

ITEM_NO | ORDER_NO | NAME
-------------------------
  123   |   100    | JOE
  123   |   101    | BOB
  123   |   101    | BOB
  124   |   101    | BOB
  456   |   102    | BOB

所需的输出:

ITEM_NO | ORDER_NO | NAME
-------------------------
  123   |   100    | JOE
  123   |   101    | BOB
  124   |   101    | BOB
  456   |   102    | BOB

基本上,我需要为每个唯一的ORDER_NO选择所有具有唯一ITEM_NO的行。

1 个答案:

答案 0 :(得分:0)

尝试DISTINCT选择

SELECT DISTINCT ITEM_NO, ORDER_NO, NAME
FROM <TABLE_NAME>

OR

SELECT I.ITEM_NO, I.ORDER_NO, I.NAME 
FROM (SELECT DISTINCT ITEM_NO, ORDER_NO FROM <TABLE_NAME>) AS X
JOIN <TABLE_NAME> I ON I.ITEM_NO = X.ITEM_NO AND I.ORDER_NO = x.ORDER_NO