我有2个表,其值如下所示
tblIncome(日期,收入)
tblExpense(日期,费用)
预期结果是(月,收入,费用)
答案 0 :(得分:0)
您的问题要求提供“日历表”。这个词在社区中是众所周知的,谷歌会给出很多点击。
这就是我的看法
完成表格(最好使用脚本)以满足其他所需的月份
一旦到位,您可以在此脚本中运行下面的查询,该结果将为您提供结果
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