使用php mysql查询选择具有最高值的5列

时间:2016-10-20 10:04:00

标签: php mysql database union

我需要5个具有最高值的列(值必须是每列的总和)才能生成报告。我有大约40个contury colunms,比如england_turist,polad_turists,us_turists,india_turists ... eng - 152(sum),pol - 280(sum),us - 54(sum),in - 36(sum)...和query需要选择pol - 280和eng - 152.因此查询需要对每一列求和并选择具有最高值的5列。

我从这里得到了结果,但是如何创建查询

SELECT * FROM
(
     SELECT 'Bmw' AS vrstaautomobila, SUM(bmw) AS brautomobila FROM unos_korisnika
     UNION
     SELECT 'Mercedes' AS vrstaautomobila, SUM(mercedes) AS brautomobila FROM unos_korisnika
     UNION
     SELECT 'Opel' AS vrstaautomobila, SUM(opel) AS brautomobila FROM unos_korisnika
     UNION
     SELECT 'Nissan' AS vrstaautomobila, SUM(nissan) AS brautomobila FROM unos_korisnika
     UNION
     SELECT 'Peguoet' AS vrstaautomobila, SUM(peguoet) AS brautomobila FROM unos_korisnika
     UNION
     SELECT 'Volkswagen' AS vrstaautomobila, SUM(volkswagen) AS brautomobila FROM unos_korisnika
)
AS results
ORDER BY brautomobila DESC
LIMIT 5

1 个答案:

答案 0 :(得分:1)

转置表格(将列转换为行),然后选择最高值。

while (my $filename =<*.txt>) # change the file extension whatever you want
{

    open my $fh, "<" , $filename or die "Error opening $!\n";

    #do your stuff here

}

您可以使用How to transpose mysql table rows into columns来转置您的数据,也可以使用此SQL - How to transpose?