Как я думаю, вы знаете, чтобы получить значения без требования только первого, как это:
SELECT base.item, base.state, base.county, base.by_county, state.by_state, item.by_item
FROM base
LEFT JOIN state on base.item = state.item and base.state = state.state
LEFT JOIN item on base.item = item.item
Чтобы изменить это, чтобы просто выбрать первый элемент, мы используем оконные функции - сначала добавьте их в
SELECT base.item, base.state, base.county,
base.by_county,
state.by_state, ROW_NUMBER(partition by base.by_state order by item,state and county) as RN_S,
item.by_item, ROW_NUMBER(partition by base.by_item order by item,state and county) as RN_I,
FROM base
LEFT JOIN state on base.item = state.item and base.state = state.state
LEFT JOIN item on base.item = item.item
Затем добавляем в фильтр:
SELECT item, state, county, by_county,
CASE WHEN RN_S = 1 THEN by_state ELSE NULL END AS by_state,
CASE WHEN RN_I = 1 THEN by_item ELSE NULL END AS by_item
FROM
(
SELECT base.item, base.state, base.county,
base.by_county,
state.by_state, ROW_NUMBER(partition by base.by_state order by item,state and county) as RN_S,
item.by_item, ROW_NUMBER(partition by base.by_item order by item,state and county) as RN_I,
FROM base
LEFT JOIN state on base.item = state.item and base.state = state.state
LEFT JOIN item on base.item = item.item
) x