首页 > 数据库技术 > 详细

数据库多行转换为单一列

时间:2020-11-23 09:15:22      阅读:31      评论:0      收藏:0      [点我收藏+]

数据库存储与实际显示需求不一样时,我们得写SQL来实现数据呈现:

如:

技术分享图片

 

先来看看数据表:

技术分享图片

 

技术分享图片
CREATE TABLE [dbo].[Expenses]
(
    [Date] DATE,
    [Description] NVARCHAR(40),
    [Charge] DECIMAL(18,2)
)
GO
Source Code

 

然后,我们为表填充一些数据,比如春节购买开支:

技术分享图片

 

技术分享图片
INSERT INTO [dbo].[Expenses] ([Date],[Description],[Charge]) VALUES 
(2020-01-22,N鱿鱼,305.40),
(2020-01-22,N猪肉,110.60),
(2020-01-22,N青菜,36.90),
(2020-01-22,N,30.00),
(2020-01-22,N,75.00),

(2020-01-23,N鱿鱼,200.40),
(2020-01-23,N猪肉,50.00),
(2020-01-23,N青菜,14.30),
(2020-01-23,N,30.00),
(2020-01-23,N,20.00),

(2020-01-24,N鱿鱼,460.00),
(2020-01-24,N猪肉,200.00),
(2020-01-24,N青菜,90.00),
(2020-01-24,N,50.00),
(2020-01-24,N,300.00)

GO
Source Code

 

所有数据准备完毕,现在写SQL来实现此功能:

技术分享图片

 

技术分享图片
SELECT E1.[Date],E1.[Charge] AS N鱿鱼,E2.[Charge] AS N猪肉,E3.[Charge] AS N青菜,E4.[Charge] AS N, E5.[Charge] AS N  FROM
[dbo].[Expenses] AS E1,[dbo].[Expenses] AS E2,[dbo].[Expenses] AS E3,[dbo].[Expenses] AS E4,[dbo].[Expenses] AS E5
WHERE E1.[Date] = E2.[Date] AND E2.[Date] = E3.[Date] AND E3.[Date] = E4.[Date] AND E4.[Date] = E5.[Date]
AND E1.[Description] = N鱿鱼 AND E2.[Description] = N猪肉 AND E3.[Description] = N青菜 AND E4.[Description] = N AND E5.[Description] = N  
GO
Source Code

 

数据库多行转换为单一列

原文:https://www.cnblogs.com/firebet/p/14022672.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!