sql server 查询结果列转行, 查询语句如下
select Card_ID,YEAR(Exchange_Time) 年,month(Exchange_Time) 月,COUNT(Exchange_ID) 次数
from Exchange_Log where Card_ID='800200003087'
GROUP BY Card_ID,YEAR(Exchange_Time),month(Exchange_Time)
order by YEAR(Exchange_Time)
sql server 查询结果列转行, 查询语句如下
select Card_ID,YEAR(Exchange_Time) 年,month(Exchange_Time) 月,COUNT(Exchange_ID) 次数
from Exchange_Log where Card_ID='800200003087'
GROUP BY Card_ID,YEAR(Exchange_Time),month(Exchange_Time)
order by YEAR(Exchange_Time)
让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言问题:如何将上述 SQL 查询结果的列转行,使得同一 Card_ID 的结果显示在同一行中? 回答: 可以使用 SQL Server 中的 PIVOT 和 UNPIVOT 函数将列转行或行转列。在这里,我们需要将年份和月份列转为行,以便同一 Card_ID 的结果在同一行显示。以下是实现这一转换的代码示例:
SELECT Card_ID,
[2022-09] AS Sep_2022,
[2022-10] AS Oct_2022,
[2022-11] AS Nov_2022,
[2022-12] AS Dec_2022,
[2023-01] AS Jan_2023,
[2023-02] AS Feb_2023,
[2023-03] AS Mar_2023,
[2023-04] AS Apr_2023,
[2023-05] AS May_2023,
[2023-06] AS Jun_2023,
[2023-07] AS Jul_2023,
[2023-08] AS Aug_2023,
[2023-09] AS Sep_2023,
[2023-10] AS Oct_2023,
[2023-11] AS Nov_2023,
[2023-12] AS Dec_2023,
[2024-01] AS Jan_2024,
[2024-02] AS Feb_2024
FROM (SELECT Card_ID,
CAST(YEAR(Exchange_Time) AS VARCHAR(4)) + '-' + RIGHT('0' + CAST(MONTH(Exchange_Time) AS VARCHAR(2)), 2) AS MonthYear,
COUNT(Exchange_ID) AS Count
FROM Exchange_Log
WHERE Card_ID = '800200003087'
GROUP BY Card_ID, YEAR(Exchange_Time), MONTH(Exchange_Time)) AS SourceTable
PIVOT (SUM(Count) FOR MonthYear IN ([2022-09],[2022-10],[2022-11],[2022-12],[2023-01],[2023-02],[2023-03],[2023-04],[2023-05],[2023-06],[2023-07],[2023-08],[2023-09],[2023-10],[2023-11],[2023-12],[2024-01],[2024-02])) AS PivotTable;
上述代码中,我们先使用 INNER JOIN 将 Exchange_Log 表中的 Card_ID、年份、月份和次数聚合起来,生成一个名为 SourceTable 的子查询。然后,我们调用 PIVOT 函数并使用 MonthYear 字段作为转换值,以生成名为 PivotTable 的结果集。最后,我们将 PivotTable 进行选择并重新命名以便处理数据。 以上代码将为我们提供如下的结果:
Card_ID Sep_2022 Oct_2022 Nov_2022 Dec_2022 Jan_2023 Feb_2023 Mar_2023 Apr_2023 May_2023 Jun_2023 Jul_2023 Aug_2023 Sep_2023 Oct_2023 Nov_2023 Dec_2023 Jan_2024 Feb_2024
--------------- -------- -------- -------- -------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- -------
800200003087 1 1 3 1 3 2 2 NULL 1 2 1 2 1 2 1 NULL 2 2
这个结果显示了 Card_ID = '800200003087' 的每个月的次数。每个月作为一个单独的列被展示,同一 Card_ID 的结果显示在同一行中。