查询以搜索MAX值

时间:2016-05-13 17:07:53

标签: sql sql-server

我正在尝试从我的列中获取MAX值,该值是以百分比形式创建的,并且会从nvarchar列获取来自不同内容的信息。

这是查询:

SELECT Filetype AS 'Extensão', 
COUNT(*) AS 'Nº de ficheiros',
CAST(((COUNT(Filetype) * 100.0) / (SELECT COUNT(*) FROM infofile)) AS DECIMAL(10,2)) AS 'Percentagem (%)',
SUM(Filesize) AS 'Total(KB)',
NULL AS 'Convertido para MB'
FROM infofile  
GROUP BY Filetype
UNION ALL
SELECT '---------------',
COUNT('Nº de extensões'),
((COUNT(Filetype) * 100) / (SELECT COUNT(Filetype) FROM infofile)), 
SUM(Filesize),
SUM(Filesize) / 1024 
FROM infofile

我想要做的是一个查询,它给出了此列中的MAX和MIN百分比。我试过用

SELECT MAX('Percentagem (%)') * 100 
FROM infofile

但它会给我一个错误:

  转化varchar值时转化失败'百分比(%)&#39>数据类型int。

顺便说一下,这是一个在SqlServer上使用的本地数据库

3 个答案:

答案 0 :(得分:1)

{{1}}

答案 1 :(得分:0)

您的查询失败,因为'百分比(%)'是一个以' P'开头的字符串。接着是' e'等等。

对于列别名,请使用标准SQL分隔符"MAX("Percentagem (%)")。如果您使用的是SQL Server,请使用非标准分隔符[]代替:MAX([Percentagem (%)])

最好的解决方案当然不是使用必须首先转义的列名或别名,例如MAX(percentagem)

答案 2 :(得分:0)

如果您的SQL Server版本不太旧,您可以使用窗口函数:

select 
  filetype as [Extensão], 
  count(*) as [Nº de ficheiros],
  count(*) * 100.0 / sum(count(*)) over () as [Percentagem (%)],
  sum(filesize) as [Total(KB)],
  sum(filesize) / 1024.0 as [Convertido para MB],
  min(count(*)) over () * 100.0 / sum(count(*)) over () as [Min. Percentagem (%)],
  max(count(*)) over () * 100.0 / sum(count(*)) over () as [Max. Percentagem (%)]
from infofile  
group by filetype
order by filetype;

SQL小提琴:http://sqlfiddle.com/#!6/3e0792/1

对于总计行,应该可以使用ROLLUPGROUP BY GROUPING SETS优雅地生成,但我不确定这些是如何与窗口函数一起使用的。所以我不能在这里给出好的建议。

有时,使用编程语言在应用程序中获取SQL之外的总计行是最容易的。

这是一个有效的完整查询:

select
  [Extensão], 
  sum([Nº de ficheiros]) as [Nº de ficheiros],
  round(sum([Percentagem (%)]), 2) as [Percentagem (%)],
  sum([Total(KB)]) as [Total(KB)],
  round(sum([Convertido para MB]),2) as [Convertido para MB],
  round(min([Min. Percentagem (%)]), 2) as [Min. Percentagem (%)],
  round(max([Max. Percentagem (%)]), 2) as [Max. Percentagem (%)]
from
(
  select 
    filetype as [Extensão], 
    count(*) as [Nº de ficheiros],
    count(*) * 100.0 / sum(count(*)) over () as [Percentagem (%)],
    sum(filesize) as [Total(KB)],
    sum(filesize) / 1024.0 as [Convertido para MB],
    min(count(*)) over () * 100.0 / sum(count(*)) over () as [Min. Percentagem (%)],
    max(count(*)) over () * 100.0 / sum(count(*)) over () as [Max. Percentagem (%)]
  from infofile  
  group by filetype
) per_filetype
group by rollup([Extensão])
order by case when [Extensão] is null then 2 else 1 end, [Extensão];

SQL小提琴:http://sqlfiddle.com/#!6/3e0792/29