加入子查询

时间:2017-11-30 14:46:03

标签: sql sql-server join

我试图找到binnum的不同值。然而,我需要保持origrec在select中,因为它是一个唯一的id。只要存在与不同的bin相关联的值,origrec值是什么并不重要。

我试图在联接中执行此操作。但是,在执行子查询内连接时,我似乎仍然获得所有值。我哪里出错了,纠正这个问题的最佳方法是什么?

完整代码:

SELECT distinct d.BINNUM
    , d.LOCATIONNAME
    , d.LOCATIONTYPE
    , d.ORIGREC 
FROM DLOCATION D 
inner join 
( 
    SELECT distinct d1.binnum 
    FROM dlocation d1 
    GROUP BY d1.binnum
) as D1 On d.binnum = d1.binnum

第一次查询:

SELECT distinct d.BINNUM,d.LOCATIONNAME,d.LOCATIONTYPE,d.ORIGREC FROM DLOCATION D

会回来:

BINNUM  LOCATIONNAME    LOCATIONTYPE    ORIGREC
1       Bruker          RawMaterial     31
1       Bruker          RawMaterial     32
200     WetChem         RawMaterial     33
200     WetChem         RawMaterial     34
555     WetChem         RawMaterial     19
555     WetChem         RawMaterial     21
555     WetChem         RawMaterial     23
555     WetChem         RawMaterial     30
998     WetChem         RawMaterial     26
1002    Forage Cooler   Forage          27
2008    XRF Press       International   29
2009    Long Term       International   28

第二次查询:

SELECT distinct d1.binnum FROM dlocation d1 GROUP BY d1.binnum

会回来:

BINNUM
1
200
555
998
1002
2008
2009

为什么内部联接仍然会在这两者之间提供所有结果?

BINNUM  LOCATIONNAME    LOCATIONTYPE    ORIGREC
1       Bruker          RawMaterial     31
1       Bruker          RawMaterial     32
200     WetChem         RawMaterial     33
200     WetChem         RawMaterial     34
555     WetChem         RawMaterial     19
555     WetChem         RawMaterial     21
555     WetChem         RawMaterial     23
555     WetChem         RawMaterial     30
998     WetChem         RawMaterial     26
1002    Forage Cooler   Forage          27
2008    XRF Press       International   29
2009    Long Term       International   28

我怎样才能获得第二个查询中看到的BinNum值,所以它看起来像这样?

BINNUM  LOCATIONNAME    LOCATIONTYPE    ORIGREC
1       Bruker          RawMaterial     31
200     WetChem         RawMaterial     33
555     WetChem         RawMaterial     19
998     WetChem         RawMaterial     26
1002    Forage Cooler   Forage          27
2008    XRF Press       International   29
2009    Long Term       International   28

1 个答案:

答案 0 :(得分:1)

一些基本的聚合可以做到这一点。这里也不需要子查询。除非您有一个区分大小写的排序规则,并且DLOCATION和dlocation实际上是不同的表。假设你不是这种情况,可以大大简化。

SELECT d.BINNUM
    , d.LOCATIONNAME
    , d.LOCATIONTYPE
    , MIN(d.ORIGREC)
FROM DLOCATION D 
GROUP BY d.BINNUM
    , d.LOCATIONNAME
    , d.LOCATIONTYPE