MySQLSelect单列变成多列
MySQL Select single column into multiple column
所以,我有以下 table(粗例):
CREATE TABLE budget_details(
detail_id INT PRIMARY KEY,
budget_id INT FOREIGN KEY,
detail_month VARCHAR(16),
total DECIMAL(18,2)
)
我正在尝试 Select 单行 budget_id
并且每个月(例如一月、二月等)都有不同的列来显示它们的总数,而所有其他月份为空, 显示 0, idc, 像这样 Example of results
我知道重新创建 table 会更容易,但它是一个旧软件,我会破坏很多东西
感谢任何帮助
下面的查询提供了如图所示的结果。
SELECT
detail_id,
budget_id,
CASE WHEN detail_month = 'January' THEN total END AS 'January',
CASE WHEN detail_month = 'February' THEN total END AS 'February',
CASE WHEN detail_month = 'March' THEN total END AS 'March'
FROM
budget_details
ORDER BY
detail_id,
budget_id
所以,我有以下 table(粗例):
CREATE TABLE budget_details(
detail_id INT PRIMARY KEY,
budget_id INT FOREIGN KEY,
detail_month VARCHAR(16),
total DECIMAL(18,2)
)
我正在尝试 Select 单行 budget_id
并且每个月(例如一月、二月等)都有不同的列来显示它们的总数,而所有其他月份为空, 显示 0, idc, 像这样 Example of results
我知道重新创建 table 会更容易,但它是一个旧软件,我会破坏很多东西
感谢任何帮助
下面的查询提供了如图所示的结果。
SELECT
detail_id,
budget_id,
CASE WHEN detail_month = 'January' THEN total END AS 'January',
CASE WHEN detail_month = 'February' THEN total END AS 'February',
CASE WHEN detail_month = 'March' THEN total END AS 'March'
FROM
budget_details
ORDER BY
detail_id,
budget_id