查询以组合两个子查询的结果

时间:2012-05-27 10:35:16

标签: sql-server-2005 stored-procedures

我有2个表,其值如下所示

tblIncome(日期,收入)

  • 12/02/2012 1000
  • 14/02/2012 2000
  • 10/03/2012 1500
  • 05/03/2012 5000

tblExpense(日期,费用)

  • 05/02/2012 1200
  • 10/02/2012 1000
  • 15/03/2012 2000

预期结果是(月,收入,费用)

  • 2月3000 2200
  • 2000年3月6500

1 个答案:

答案 0 :(得分:0)

您的问题要求提供“日历表”。这个词在社区中是众所周知的,谷歌会给出很多点击。

这就是我的看法

enter image description here

完成表格(最好使用脚本)以满足其他所需的月份

一旦到位,您可以在此脚本中运行下面的查询,该结果将为您提供结果

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