資料庫存儲與實際顯示需求不一樣時,我們得寫SQL來實現數據呈現: 如: 先來看看數據表: CREATE TABLE [dbo].[Expenses] ( [Date] DATE, [Description] NVARCHAR(40), [Charge] DECIMAL(18,2) ) GO Sour ...
資料庫存儲與實際顯示需求不一樣時,我們得寫SQL來實現數據呈現:
如:
先來看看數據表:
CREATE TABLE [dbo].[Expenses] ( [Date] DATE, [Description] NVARCHAR(40), [Charge] DECIMAL(18,2) ) GOSource 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) GOSource 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'米' GOSource Code