2016-12-16 97 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