子查询,我可以计算从第一个查询中出现名称的次数

时间:2016-05-12 09:23:18

标签: sql sql-server subquery

这是我目前的代码:

select Name, ECU, Identifier, Value, Max(Filetime) as "Filetime"
from dbo.view_1
where ECU='EBS7' and Identifier='88' and Value='2459579' or identifier ='87' and Value='2431629'
group by Name, ECU, Identifier, Value
ORDER BY
    MAX(Name) ASC 

这是我得到的结果:Result of query

我想要某种子查询或者计算名称出现次数的东西。我们可以看到Agon出现两次而Apollo Akka只出现过一次。

关于我应该写什么的任何提示?

2 个答案:

答案 0 :(得分:1)

您可以使用相关的子查询:

Select Name, ECU, Identifier, Value,
       Max(Filetime) as "Filetime",
       (select count(*)
       from dbo.view_1 t2 
       where t2.Name = t1.Name and
             ECU ='EBS7' and 
             ((Identifier='88' and Value='2459579') or 
             (identifier ='87' and Value='2431629')) as cnt
from dbo.view_1 t1
where ECU ='EBS7' and 
      ((Identifier='88' and Value='2459579') or 
      (identifier ='87' and Value='2431629'))
group by Name, ECU, Identifier, Value
ORDER BY MAX(Name) ASC 

答案 1 :(得分:0)

我不知道MySQL(你实际使用的是哪个产品?),但在MS-SQL中这个

ORDER BY MAX(Name) ASC

甚至不会编译。您不能按不在SELECT列表中的列进行排序。

如果您想获取原始结果集,并且在集合中使用名称频率,并且您正在使用MS-SQL,则可以使用CTE:

WITH theset AS 
(select Name, ECU, Identifier, Value, Max(Filetime) as "Filetime"
from dbo.view_1
where ECU='EBS7' and Identifier='88' and Value='2459579' or identifier ='87' and Value='2431629'
group by Name, ECU, Identifier, Value)

SELECT set.*,CountNames.NameCount
FROM
    theset set
INNER JOIN
    (SELECT Name,Count(*) AS NameCount FROM theset GROUP BY Name) CountNames
ON set.Name=CountNames.Name