dqu94359 2017-04-16 21:24
浏览 57
已采纳

我的SQL数据透视查询返回错误,虽然似乎没有

My SQL query is:

SELECT * FROM 
(SELECT * FROM transactions) AS T1
PIVOT(SUM(amount) FOR month IN([March], [April], [May])) AS pvt

My Table is as follows:

id  payee       amount  month    
1   Tom         90      March
3   Tom         66      April
4   Tom         89      May
10  Jasmine     125     April
11  Nancy       151     March
12  Jasmine     175     April
13  Nancy       152     April

My desired output is:

payee       March  April   May
Tom         90     66      89
Jasmine     --     300     --
Nancy       151    152     --

I am running this query in a phpMyAdmin for my website the Error presented is as follows:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'PIVOT(SUM(amount) FOR month IN([March], [April], [May])) AS pvt

  • 写回答

1条回答 默认 最新

  • dongwenxiu5200 2017-04-17 20:08
    关注

    There is no PIVOT in MySQL, no CROSSTAB, no similar syntax. You have to build pivot tables by hand. A common technique is called conditional aggregation, and can be used this way:

    SELECT `payee`
        , SUM(CASE WHEN `month` = 'March' THEN `amount` END) AS `March`
        , SUM(CASE WHEN `month` = 'April' THEN `amount` END) AS `April`
        , SUM(CASE WHEN `month` = 'May' THEN `amount` END) AS `May` 
      FROM `transactions`
      GROUP BY `payee`;
    

    GROUP BY is crucial, because it restricts the scope of the aggregate function SUM. It is applied before calculation and it says there has to be only one output record per value of payee. Then I could write SUM(amount) to compute the sum of all amounts for that value of payee (ordinary aggregation) but I insert another condition SUM(CASE WHEN ... THEN ... END) and I do conditional aggregation.

    Using SUM without GROUP BY would compute the sum across the whole table.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?