仅返回与表1上的ID匹配的值

时间:2015-01-09 23:23:34

标签: sql crystal-reports-xi

我已经尝试了所有可能的连接和子查询但是我不能让数据只返回表2中与供应商ID完全匹配的一个值。如果我没有包含在查询中的地址,我会得到一个供应商ID的命中。我怎样才能做到这一点,当我添加地址时,我只想要在添加地址之前获得的一个供应商。

表1中的供应商必须是VEN-CLASS IS NOT NULL。

Image from the query

这是我上次使用子查询的尝试:

SELECT DISTINCT APVENMAST.VENDOR_GROUP,
            APVENMAST.VENDOR,
            APVENMAST.VENDOR_VNAME,
            APVENMAST.VENDOR_CONTCT,
            APVENMAST.TAX_ID,
            Subquery.ADDR1
 FROM (TEST.dbo.APVENMAST APVENMAST
    INNER JOIN
    (SELECT APVENADDR.ADDR1,
            APVENADDR.VENDOR_GROUP,
            APVENADDR.VENDOR,
            APVENMAST.VEN_CLASS
       FROM TEST.dbo.APVENADDR APVENADDR
            INNER JOIN TEST.dbo.APVENMAST APVENMAST
               ON     (APVENADDR.VENDOR_GROUP = APVENMAST.VENDOR_GROUP)
                  AND (APVENADDR.VENDOR = APVENMAST.VENDOR)
      WHERE (APVENMAST.VEN_CLASS IS NOT NULL)) Subquery
       ON     (APVENMAST.VENDOR_GROUP = Subquery.VENDOR_GROUP)
          AND (APVENMAST.VENDOR = Subquery.VENDOR))
   INNER JOIN TEST.dbo.APVENLOC APVENLOC
      ON     (APVENMAST.VENDOR_GROUP = APVENLOC.VENDOR_GROUP)
         AND (APVENMAST.VENDOR = APVENLOC.VENDOR)
 WHERE (APVENMAST.VEN_CLASS IS NOT NULL)

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT APVENMAST.VENDOR_GROUP
, APVENMAST.VENDOR
, APVENMAST.VENDOR_VNAME
, APVENMAST.VENDOR_CONTCT
, APVENMAST.TAX_ID
, APVENADDR.ADDR1
FROM TEST.dbo.APVENMAST APVENMAST
INNER JOIN (
    select VENDOR_GROUP, VENDOR, ADDR1
    , row_number() over (partition by VENDOR_GROUP, VENDOR order by ADDR1) r
    from TEST.dbo.APVENADDR
) APVENADDR
ON  APVENADDR.VENDOR_GROUP = APVENMAST.VENDOR_GROUP
AND APVENADDR.VENDOR = APVENMAST.VENDOR
AND APVENADDR.r = 1
--do you need this table; you're not using it...
--INNER JOIN TEST.dbo.APVENLOC APVENLOC
--ON  APVENMAST.VENDOR_GROUP = APVENLOC.VENDOR_GROUP
--AND APVENMAST.VENDOR = APVENLOC.VENDOR
WHERE APVENMAST.VEN_CLASS IS NOT NULL
--if the above inner join was to filter results, you can do this instead:
and exists (
    select top 1 1 
    from TEST.dbo.APVENLOC APVENLOC
    ON  APVENMAST.VENDOR_GROUP = APVENLOC.VENDOR_GROUP
    AND APVENMAST.VENDOR = APVENLOC.VENDOR
)

答案 1 :(得分:0)

我在APVENLOC表中找到了另一个列,我可以过滤该列来获取唯一的供应商。如果供应商地址是主办公室,则供应商位置设置为空白。

比我想象的要容易!

SELECT DISTINCT APVENMAST.VENDOR_GROUP,
            APVENMAST.VENDOR,
            APVENMAST.VENDOR_VNAME,
            APVENADDR.ADDR1,
            APVENMAST.VENDOR_SNAME,
            APVENADDR.LOCATION_CODE,
            APVENMAST.VEN_CLASS
FROM TEST.dbo.APVENMAST APVENMAST
   INNER JOIN TEST.dbo.APVENADDR APVENADDR
      ON     (APVENMAST.VENDOR_GROUP = APVENADDR.VENDOR_GROUP)
         AND (APVENMAST.VENDOR = APVENADDR.VENDOR)
WHERE (APVENADDR.LOCATION_CODE = '    ')

沙基