将多行更改为一行 - 多列

时间:2011-08-07 23:18:36

标签: mysql

出于某种原因,我必须这样做。我的查询结果如下:

limit     usage     tariff     total                  
0 10      10          700       7000                   
11 20     10          900       9000                   
21 30     10         1800      18000                  
31 >      11         2700      29700 

查询最多返回4行(如上所述)或有时只返回3行。 我想将行更改为这样的一行和多列(下面的列表只有一行):

limit1     usage1     tariff1     total1   limit2     usage2     tariff2     total2               
 0 10      10          700          7000    11 20     10          900         9000       


limit3     usage3     tariff3     total3   limit4     usage4     tariff4     total4                       
 21 30     10         1800         18000     31 >     11          2700       29700

如果查询只返回3行,则limit4中的值直到total4将为空。我不知道该怎么做。

EDITED

我添加了一个ID列,因此列表将是:

ID   limit     usage     tariff     total                  
 1   0 10      10          700       7000                   
 2   11 20     10          900       9000                   
 3   21 30     10         1800      18000                  
 4   31 >      11         2700      29700

我尝试将它排成一行:

SELECT e.*,f.id AS id4,f.limit AS limit4,f.usage AS usage4,f.tariff AS tariff4,f.total AS total4 
FROM  
(SELECT c.*,d.id AS id3,d.limit AS limit3,d.usage AS usage3,d.tariff AS tariff3,d.total AS total3 
FROM  
(SELECT b.id AS id1,b.limit AS limit1,b.usage AS usage1,b.tariff AS tariff1,b.total AS total1,
a.id AS id2,a.limit AS limit2,a.usage AS usage2,a.tariff AS tariff2,a.total AS total2 
FROM testtariff a 
INNER JOIN testtariff b ON a.id!=b.id 
LIMIT 1) c INNER JOIN testtariff d ON c.id1 != d.id AND c.id2 != d.id
LIMIT 1) e INNER JOIN testtariff f ON e.id1 != f.id AND e.id2 != f.id 
AND e.id3 != f.id 
LIMIT 1

它按照我预期的4行工作,但不能用于3行。我应该使用光标吗?

1 个答案:

答案 0 :(得分:0)

这通常被称为“枢轴”。这是你如何做到的:

select
    '0 10' as limit1,
    sum(limit between 0 and 10 * usage) as usage1,
    sum(limit between 0 and 10 * tariff) as tariff1,
    sum(limit between 0 and 10 * usage * tariff) as total1,
    '11 20' as limit2,
    sum(limit between 11 and 20 * usage) as usage2,
    sum(limit between 11 and 20 * tariff) as tariff2,
    sum(limit between 11 and 20 * usage * tariff) as total2,
    -- etc
from mytable
group by 1,5 -- etc

这是有效的,因为limit between x and x如果为1,如果为0则为{{1}},因此使用乘以这是将结果过滤到不同组的简单方法。