2016-12-16 61 views
-2

我需要設置欄中的 「產品ID」 一個不同於我下面的查詢:SQL DISTINCT TOP 30

SELECT TOP 30 s.fid, s.productid, s.partsreplaced, s.labor, p.part_number, p.name, p.img_small, p.discontinued 
FROM frequentrepairs s 
INNER JOIN products p ON s.productid = p.id  
ORDER BY p.part_number ASC 

我嘗試這樣做:

SELECT TOP 30 s.fid, s.productid, s.partsreplaced, s.labor, p.part_number, p.name, p.img_small, p.discontinued 
FROM (SELECT DISTINCT productid FROM frequentrepairs) frequentrepairs s 
INNER JOIN products p ON s.productid = p.id  
ORDER BY p.part_number ASC 

很抱歉不能提供數據樣本。下面是我的表FrequentRepairs樣子:

enter image description here

所以基本上,我不想顯示相同的「產品ID」兩次。

+4

發生了什麼事?我們不知道你的數據是什麼樣的,或者你的輸出是什麼樣的。 – dfundako

+0

你想要完成什麼英語?你不能區分一個領域。表FrequentRepairs似乎有哪幾個部位都可能綁回單品這就是爲什麼你得到多個產品ID ...提供一些示例數據和預期的結果幫告訴你想要做什麼了商店,爲什麼。 – xQbert

+0

你想要1)30個任意行,每個行都有唯一的產品ID? 2)屬於TOP 30產品ID的所有行? 3)完全是另一回事?從不正確的SQL中分離所需的輸出很困難。 –

回答

0

重新開始: 我有是我不明白的問題/問題還沒有問題。

假設:

  1. Products.ID是主鍵。
  2. FrequentRepairs.ProductID是一個外鍵Products.ID
  3. 產品和FrequentRepairs之間的關係是1對多
  4. 的你想達到什麼樣的總體目標是頂級的30份名單參與最多的維修?

SELECT TOP 30 
     max(s.fid) as max_fid 
    , p.productid 
    , max(s.partsreplaced) as partsReplaced --(just picking 1) 
     --if it needs to be coorlated to the max_FID then we would have 
     --to dos something different 
    , sum(s.labor) as Sum_labor 
    , p.part_number 
    , p.name 
    , p.img_small 
    , p.discontinued 
FROM frequentrepairs s 
INNER JOIN products p 
    ON s.productid = p.id  
GROUP BY p.Part_number, P.Name, p.img_small, p.Discontinued, 
ORDER BY count(p.part_number) DESC, part_number ASC 
+0

在's'附近獲得錯誤的語法。在這。 – Brasciole

+0

有'frequentrepairs s'刪除'frequentrepairs' – xQbert

+0

實際上,它認爲應該從(SELECT DISTINCT的productid FROM frequentrepairs S),但現在我得到的內部連接錯誤(預期AS,ID或QUOTED_ID) – Brasciole