将SQL结果返回到一行

时间:2017-03-21 15:15:10

标签: php sql

我尝试使用PHP脚本填充HTML表格,该脚本运行SQL查询,返回以下结果(示例):

 UserID  |  Name  |  Month  | Value  |
   1     |  Joe   |   Jan   | 123.00 |
   1     |  Joe   |   Feb   | 22.00  |
   1     |  Joe   |  March  | 32.50  |
  21     |  Derek |   Jan   | 45.76  |
  21     |  Derek |  March  | 12.31  |

但是当我想在PHP中填充表格时,我希望表格看起来像这样:

 Name   |   January  |  February  |  March  |
  Joe   |    123.00  |   22.00    |  32.50  |
 Derek  |    45.76   |            |  12.31  |

但是当使用PHP while循环生成表时,它会执行以下操作,这是我期望的,因为它只是循环遍历每个获取的行:

 Name   |   January  |  February  |  March  |
  Joe   |    123.00  |            |         |
  Joe   |    22.00   |            |         |
  Joe   |    32.500  |            |         |
 Derek  |    45.76   |            |         | ... etc`

正如我所说,我希望它能以这种方式运行,但无论如何都要在第二个例子中显示它。

我已经制定了一些逻辑来将值放在正确的位置,但它仍然在一个单独的行上,所以目前它看起来像这样,这不是理想的

 Name   |   January  |  February  |  March  |
  Joe   |    123.00  |            |         |
  Joe   |            |    22.00   |         |
  Joe   |            |            |  32.50  |
 Derek  |    45.76   |            |         | 

我希望我不会错过任何明显的内容,但我已经看过SQL中的几个解决方案,但似乎无法让它发挥作用。

任何帮助都将不胜感激。

编辑:

道歉,我的SQL查询从两个不同的表中获取数据,因为我正在比较值,所以我的理解是我无法使用GROUP BY语句。这是我的SQL查询:

SELECT dbo_tstUser.UserID, dbo_tstUser.Name, dbo_tstUser.Month, dbo_tstUser.Value, dbo_tstUserImport.Value FROM dbo_tstUser INNER JOIN dbo_tstUserImport ON dbo_tstUser.UserID = dbo_tstUserImport.UserID;

2 个答案:

答案 0 :(得分:0)

您需要在SQL中添加GROUP BY name语句: -

SELECT UserID, Name, Month, Value
FROM table
GROUP BY Name 

编辑: -

SELECT dbo_tstUser.UserID, dbo_tstUser.Name, dbo_tstUser.Month, dbo_tstUser.Value, dbo_tstUserImport.Value 
FROM dbo_tstUser 
INNER JOIN dbo_tstUserImport ON dbo_tstUser.UserID = dbo_tstUserImport.UserID
GROUP BY dbo_tstUser.UserID;

答案 1 :(得分:0)

您可以使用聚合来进行旋转:

select UserId, name, 
    max(case when Month = 'Jan' then value end) as January,
    max(case when Month = 'Feb' then value end) as February,
    max(case when Month = 'March' then value end) as March
from your_table
group by UserId, name;

如果您不想在结果中使用UserId,可以使用:

select name, 
    max(case when Month = 'Jan' then value end) as January,
    max(case when Month = 'Feb' then value end) as February,
    max(case when Month = 'March' then value end) as March
from your_table
group by UserId, name;

请注意,我将UserId保留在group by子句中,以便将具有相同名称的不同人员分开。

相关问题