【问题标题】:Need Simple Query in Sql serverSql server 中需要简单查询
【发布时间】:2016-12-31 04:32:42
【问题描述】:

我的标准:

我有一个分销商(父表),他有很多零售商(子表)。我需要最后加入的零售商名称。

即

Distributor List  |  Total No. Retailer    |     Last Joined Retailer Name

我的查询是:

select distName,  
       count(retailerName) as TotalRetailer,  
       max(retailerName) as lastPosted,  
       max(lastjoinRetail) as lastJoindate 
from distributor d
  right outer join retailer r on d.distNo = r.retailNo
                             and r.status = 0 
                             and d.status = 0
group by distName.....

我没有最后一次加入“零售商名称”?

【问题讨论】:

    标签: sql-server select right-join


    【解决方案1】:
    select [Distributor_Name]
        , [Total_No._Retailer]
        , [Last date]
        , (select name from tbl_Retailer where [Last date] = CreatedDate) AS [Last Joined Retailer Name]
    from
    (
        select
            d.Name AS 'Distributor_Name'
            ,count(R.name) AS 'Total_No._Retailer'
            ,max(R.CreatedDate) as 'Last date'
        from tbl_Distributor AS D
        inner join tbl_Retailer AS R on D.id = R.DistributorId
        Group by D.Name
    ) as T
    order by [Distributor_Name]
    

    列名可能不匹配

    【讨论】:

    • 感谢回复我的查询,返回错误,子查询返回多个查询?....
    【解决方案2】:

    根据您的问题,我创建了一些示例表并能够获得请求的输出。看看这是否有帮助。

    DECLARE @distributor TABLE 
      ( 
         id INT,NAME VARCHAR(100) 
      ) 
    
    INSERT INTO @distributor 
    VALUES      (1,'D1'), 
                (2,'D2') 
    
    DECLARE @retailer TABLE 
      ( 
         id INT,NAME VARCHAR(100),distid INT,joindate DATE 
      ) 
    
    INSERT INTO @retailer 
    VALUES      (1,'R1',1,'08/01/2016'), 
                (2,'R2',1,'08/02/2016'), 
                (3,'R3',1,'08/03/2016'), 
                (4,'R4',2,'08/01/2016') 
    
    SELECT DISTINCT a.NAME,First_value(b.NAME) 
                             OVER( 
                               partition BY a.id 
                               ORDER BY b.joindate DESC ) last_retail_name, 
                    First_value(b.joindate) 
                                    OVER( 
                                      partition BY a.id 
                                      ORDER BY b.joindate DESC ) last_retail_date 
    FROM   @distributor a 
           INNER JOIN @retailer b 
                   ON a.id = b.distid 
    

    【讨论】:

    • 感谢我的查询回复,我有一个问题,我只为拥有零售商的分销商获取显示。如果分销商没有零售商,则不显示这些记录??.....
    • 把inner join改成left join,连没有retailer的经销商也能得到
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-04
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 2016-04-05
    相关资源
    最近更新 更多