UNION SQL - 每次调用SELECT语句时都向结果添加一个新列

时间:2013-08-12 13:15:57

标签: sql sql-server-2008

以下代码编译了几个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

我如何实现这些结果?

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

1 个答案:

答案 0 :(得分: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中选择双引号或方括号,因此有更好的选择。