在sql中选择一个名称

时间:2014-01-22 09:58:44

标签: sql sql-server select sql-order-by top-n

我使用以下查询从类别表中选择类别名称

select Category.Name 
  from Product 
    inner  join ProductCategory on ProductCategory.PID=Product.PID 
    inner join ProductMaterial on ProductMaterial.PID=Product.PID 
    left join Category on Category.NodeId=ProductCategory.CID 
  where PID in('2233','4432','5665','1252')  
  group by ProductCategory.CID, ProductMaterial.MID,Category.DanishName

查询正在运行此查询的结果是

Electronics
Electronics
Electronics
Home and Garden

我只想选择大多数类别名称,这里我只需要电子设备。如何得到这个。谢谢提前寻求帮助...>>

1 个答案:

答案 0 :(得分:2)

试试这个:

<强>的MySQL

SELECT A.name, COUNT(A.name) nameCnt
FROM (SELECT C.Name 
      FROM Product P 
      INNER JOIN ProductCategory PC ON PC.PID=P.PID 
      INNER JOIN ProductMaterial PM ON PM.PID=P.PID 
      INNER JOIN Category C ON C.NodeId=PC.CID 
      WHERE PID IN('2233','4432','5665','1252')  
      GROUP BY PC.CID, PM.MID, C.DanishName 
    ) AS A 
GROUP BY A.name 
ORDER BY nameCnt DESC LIMIT 1;

SQL Server

SELECT TOP 1 A.name, COUNT(A.name) nameCnt
FROM (SELECT C.Name 
      FROM Product P 
      INNER JOIN ProductCategory PC ON PC.PID=P.PID 
      INNER JOIN ProductMaterial PM ON PM.PID=P.PID 
      INNER JOIN Category C ON C.NodeId=PC.CID 
      WHERE PID IN('2233','4432','5665','1252')  
      GROUP BY PC.CID, PM.MID, C.DanishName 
    ) AS A 
GROUP BY A.name 
ORDER BY nameCnt DESC;