我有 2 个表,其值如下所示
tblIncome(日期,收入)
- 2012 年 12 月 2 日 1000
- 14/02/2012 2000
- 2012 年 10 月 3 日 1500
- 2012 年 5 月 3 日 5000
tblExpense(日期,费用)
- 2012 年 5 月 2 日 1200
- 2012 年 10 月 2 日 1000
- 15/03/2012 2000
预期结果是(月、收入、费用)
- 二月 3000 2200
- 三月 6500 2000
我有 2 个表,其值如下所示
tblIncome(日期,收入)
tblExpense(日期,费用)
预期结果是(月、收入、费用)
您的问题要求提供“日历表”。这个词在社区中是众所周知的,谷歌会给出很多点击。
这就是我的样子
完成所需的其他月份的表格(最好使用脚本)
一旦到位,您可以在此脚本中运行下面的查询,该查询将为您提供结果
CREATE TABLE [dbo].[Calendar](
[MonthName] [varchar](20) NULL,
[StartdateInclusive] [datetime] NULL,
[EnddateExclusive] [datetime] NULL
)
INSERT [dbo].[Calendar] ([MonthName], [StartdateInclusive], [EnddateExclusive]) VALUES (N'February', CAST(0x00009FEA00000000 AS DateTime), CAST(0x0000A00700000000 AS DateTime))
INSERT [dbo].[Calendar] ([MonthName], [StartdateInclusive], [EnddateExclusive]) VALUES (N'March', CAST(0x0000A00700000000 AS DateTime), CAST(0x0000A02600000000 AS DateTime))
CREATE TABLE [dbo].[tblIncome](
[Date] [datetime] NULL,
[Income] [money] NULL
)
INSERT [dbo].[tblIncome] ([Date], [Income]) VALUES (CAST(0x00009FF500000000 AS DateTime), 1000.0000)
INSERT [dbo].[tblIncome] ([Date], [Income]) VALUES (CAST(0x00009FF700000000 AS DateTime), 2000.0000)
INSERT [dbo].[tblIncome] ([Date], [Income]) VALUES (CAST(0x0000A01000000000 AS DateTime), 1500.0000)
INSERT [dbo].[tblIncome] ([Date], [Income]) VALUES (CAST(0x0000A00B00000000 AS DateTime), 5000.0000)
CREATE TABLE [dbo].[tblExpense](
[Date] [datetime] NULL,
[Expense] [money] NULL
)
INSERT [dbo].[tblExpense] ([Date], [Expense]) VALUES (CAST(0x00009FEE00000000 AS DateTime), 1200.0000)
INSERT [dbo].[tblExpense] ([Date], [Expense]) VALUES (CAST(0x00009FF300000000 AS DateTime), 1000.0000)
INSERT [dbo].[tblExpense] ([Date], [Expense]) VALUES (CAST(0x0000A01500000000 AS DateTime), 2000.0000)
SELECT MonthName ,
SUM(Income) ,
SUM(Expense)
FROM ( SELECT MonthName ,
i.Income ,
NULL AS Expense
FROM dbo.Calendar c
LEFT JOIN dbo.tblIncome i ON c.StartdateInclusive <= i.Date
AND i.Date < c.enddateExclusive
UNION
SELECT MonthName ,
NULL ,
e.Expense AS Expense
FROM dbo.Calendar c
LEFT JOIN dbo.tblExpense e ON c.StartdateInclusive <= e.Date
AND e.Date < c.enddateExclusive
) AS d
GROUP BY MonthName