当前位置: 代码迷 >> Sql Server >> ms-sql left join的有关问题
  详细解决方案

ms-sql left join的有关问题

热度:57   发布时间:2016-04-24 10:10:36.0
ms-sql left join的问题

1.   set  @TemQueryStr='SELECT a.CustomerFirstName,isnull(a.Collected,0) as Collected,b.Subtotal,(b.Subtotal+ExpressFee-Discount) AS Total FROM ProductOrder a INNER JOIN
(SELECT OrderId,SUM(Price*Quantity) AS Subtotal FROM ProductOrderItem GROUP BY OrderId) b
ON a.OrderId=b.OrderId where ISNULL(Deleted,0)=0 AND DisposalState <>6 ',

2.   set  @TemQueryStr=' select CustomerFirstName,sum(Total) as Total,sum(Collected) as Collected,sum(Total-Collected) as blance  from ('+@TemQueryStr+') a group by CustomerFirstName '

3.  set @QueryStr='select a.*,b.postdate from ('+@TemQueryStr+') as a left join ProductOrder b on a.CustomerFirstName=b.CustomerFirstName '


执行

select CustomerFirstName,Postdate from ProductOrder

得到

而执行上面的第二步得到


执行上面的第三步得到



我想问一下,为什么 left join应有的作用没有效果的,这里感觉应该是right join 的作用的,为什么,求大神指点!


------解决方案--------------------
类似这样,这个跟是否left还是inner join无关

SELECT  a.CustomerFirstName ,
        a.total ,
        a.Collected ,
        a.blance ,
        MAX(b.postdate) postdate
FROM    ( SELECT    CustomerFirstName ,
                    SUM(Total) AS Total ,
                    SUM(Collected) AS Collected ,
                    SUM(Total - Collected) AS blance
          FROM      ( SELECT    a.CustomerFirstName ,
                                ISNULL(a.Collected, 0) AS Collected ,
                                b.Subtotal ,
                                ( b.Subtotal + ExpressFee - Discount ) AS Total
                      FROM      ProductOrder a
                                INNER JOIN ( SELECT OrderId ,
                                                    SUM(Price * Quantity) AS Subtotal
                                             FROM   ProductOrderItem
                                             GROUP BY OrderId
                                           ) b ON a.OrderId = b.OrderId
                      WHERE     ISNULL(Deleted, 0) = 0
                                AND DisposalState <> 6
                    ) a
          GROUP BY  CustomerFirstName
        ) AS a
        LEFT JOIN ProductOrder b ON a.CustomerFirstName = b.CustomerFirstName
  相关解决方案