像加入SQL

时间:2018-01-08 08:57:53

标签: sql tsql

过去几天我一直在努力解决这个问题。

我正在将Excel电子表格转换为SSRS报告,但Excel Vlookup的便利性阻止我产生可重复的结果。

我正在尝试在SQL语句中加入表的第一行。

partnumber
==========
ABC123
XYZ999

详细

account  customer  mapped
=======  ========  ======
AA01     ABC123    POOL
UU08     ABC123    POOL
BH09     ABC123    POOL
AA01     XYZ999    CAR

我想获取 head 表中每个partnumber的映射值。 我不在乎细节表中的每个部件号都有多个帐号代码 - 只使用其中一个就足够了。

我的结果应该是

结果

partnumber  mapped
==========  ======
ABC123      POOL
XYZ999      CAR

我已阅读其他与此相关的Stack Overflow文章,但我无法将其转换为我的要求 SQL Server: How to Join to first row

我的数据样本位于http://sqlfiddle.com/#!6/32d6d/1

对于那些比我有更多SQL经验的人,能否解释一下我做错了什么?

谢谢

3 个答案:

答案 0 :(得分:1)

如果您想根据account说明而任意保留匹配的第一条记录,那么您可以尝试使用ROW_NUMBER

SELECT partnumber, mapped
FROM
(
    SELECT
        h.partnumber,
        d.mapped,
        ROW_NUMBER() OVER (PARTITON BY h.partnumber ORDER BY d.account) rn
    FROM Head h
    LEFT JOIN Detail d
        ON h.partnumber = d.customer
) t
WHERE t.rn = 1;

但如果值真的无关紧要,那么简单的GROUP BY查询可能最有意义:

SELECT
    h.partnumber,
    MAX(d.mapped) AS mapped
FROM Head h
LEFT JOIN Detail d
    ON h.partnumber = d.customer
GROUP BY
    h.partnumber;

答案 1 :(得分:0)

如果只能打开,则可以使用distinct

select distinct partnumber, mapped
from Head
inner join detail
on Head.partnumber = detail.customer

如果您要排除其他可能的条目,请使用CTE和row_number()

with CTE as
(
select customer, 
       mapped, 
       row_number() over (partion by customer order by mapped) as rn
from detail
)
select partnumber, mapped
from Head
inner join CTE
on customer = partnumber
and CTE.rn = 1

答案 2 :(得分:0)

这应该是上述情况的简单查询

SELECT DISTINST(A.PARTNUMBER),
    B.MAPPED
FROM HEAD AS A
INNER JOIN DETAIL AS B ON A.PARTNUMBER = B.CUSTOMER;