2016-08-24 42 views
2

我的准则:需要在Sql服务器简单查询

我有一个经销商(父表),谁有很多零售商(儿童表)。我需要最后加入零售商名称。

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..... 

我没有得到最后加入 “零售商名称”?根据您的问题

回答

0
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] 

可能不匹配的列名

+0

感谢回答我的查询,其中子查询返回铁道部é超过一个查询返回的错误?.... – Suttipasanga

0

,我创造了一些示例表,并能得到所要求的输出。看看这是否有帮助。

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 
+0

感谢我的查询回复,在这里我有一个问题,我只得到了显示器总代理谁拥有零售商。如果经销商没有零售商那些记录不显示?? ..... – Suttipasanga

+0

将内部连接变成左连接,即使没有零售商的经销商 – Muthukumar