1

下面的代码编译了几个SELECT语句。

SELECT b.User, SUM(i.ClientFee - i.CentreFee) as '1 Jan - 31 Jan'
FROM tblInvoices i
Inner Join tblBooking b
    ON i.B_ID = b.BookingID
WHERE (i.InvoiceDate BETWEEN '2012-01-01' and '2012-01-31')
GROUP BY b.User

UNION ALL

SELECT b.User, SUM(i.ClientFee - i.CentreFee) as '1 Feb - 29 Feb'
FROM tblInvoices i
Inner Join tblBooking b
    ON i.B_ID = b.BookingID
WHERE (i.InvoiceDate BETWEEN '2012-02-01' and '2012-02-29')
GROUP BY b.User

UNION ALL

SELECT b.User, SUM(i.ClientFee - i.CentreFee) as 'Total'
FROM tblInvoices i
Inner Join tblBooking b
    ON i.B_ID = b.BookingID
WHERE (i.InvoiceDate BETWEEN '2012-01-01' and '2012-02-29')
GROUP BY b.User;

结果:

User | 1 Jan - 31 Jan
----------------------
Ben  | 100.00
Tom  | 210.00
Fred | 100.00
Ben  | 250.00
Tom  | 140.00
Fred | 150.00
Ben  | 350.00
Tom  | 350.00
Fred | 250.00

我从公司数据库中的几个表中选择用户 ( b.User) 和他们的月利润 ( )。i.clientfee - i.centrfee对于每个SELECT语句运行,我需要添加一个新列来显示此语句结果。这些列的标题需要是期间的开始和结束日期,请参见下表:

User | 1 Jan - 31 Jan | 1 Feb - 29 Feb | Total
________________________________________________
Ben  |-----100.00-----|-----250.00-----| 350.00
Tom  |-----210.00-----|-----140.00-----| 350.00
Fred |-----100.00-----|-----150.00-----| 250.00

我将如何实现这些结果?

任何帮助或建议将不胜感激。

4

1 回答 1

3

你不想使用union. 使用条件聚合:

SELECT b.User,
       SUM(case when i.InvoiceDate BETWEEN '2012-01-01' and '2012-01-31'
                then i.ClientFee - i.CentreFee
           end) as "1 Jan - 31 Jan",
       SUM(case when i.InvoiceDate BETWEEN '2012-02-01' and '2012-02-29'
                then i.ClientFee - i.CentreFee
           end) as "1 Feb - 29 Feb",
       SUM(i.ClientFee - i.CentreFee) as Total
FROM tblInvoices i
Inner Join tblBooking b
    ON i.B_ID = b.BookingID
WHERE (i.InvoiceDate BETWEEN '2012-01-01' and '2012-02-29')
GROUP BY b.User;

此外,我将列别名更改为使用双引号而不是单引号。尽管允许使用单引号,但我更喜欢将它们的使用限制为字符串常量。您可以在 SQL Server 中选择双引号或方括号,因此有更好的选择。

于 2013-08-12T13:26:23.980 回答