SQL DISTINCT TOP 30

时间:2016-12-16 20:28:51

标签: sql-server

我需要在列" productid"上设置DISTINCT。来自我的查询:

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

所以基本上,我不想显示相同的" productid"两次。

1 个答案:

答案 0 :(得分:0)

重新开始: 我遇到的问题是我还不了解问题/问题。

假设:

  1. Products.ID是主键。
  2. FrequentRepairs.ProductID是Products.ID的外键
  3. 产品与FrequentRepairs之间的关系是1对多
  4. 您要实现的目标的总体目标是大多数维修中涉及的前30个部分的列表?
  5. 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