2016-08-24 44 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