MySQL自定义计算视图

时间:2015-06-02 20:59:26

标签: mysql sql database views calculated-columns

我在尝试合并我正在使用的一组查询时遇到了困难。我目前不得不执行具有不同年份和CID号码的多个查询。 (CID为1-5,年份为CurrentYear至CurrentYear-6)

当前SQL语句:

SELECT 
1 as CID,
2015 as `Year`,
(   SELECT SUM( legacy_reports_payments.AmountPaid ) * -1 AS Payments FROM  legacy_reports_payments
    WHERE   DatePaid >= "2015-01-01 00:00:00"   AND DatePaid < "2015-02-01 00:00:00"
    AND CID = 1) As PaymentsJan,
(   SELECT SUM( legacy_reports_payments.AmountPaid ) * -1 AS Payments FROM  legacy_reports_payments
    WHERE   DatePaid >= "2015-02-01 00:00:00"   AND DatePaid < "2015-03-01 00:00:00"
    AND CID = 1) As PaymentsFeb,
(   SELECT SUM( legacy_reports_payments.AmountPaid ) * -1 AS Payments FROM  legacy_reports_payments
    WHERE   DatePaid >= "2015-03-01 00:00:00"   AND DatePaid < "2015-04-01 00:00:00"
    AND CID= 1) As PaymentsMar,
...

返回:

CID  | Year | PaymentsJan | PaymentsFeb | ...
1    | 2015 | 3000.00     | 3000.00     | ...

我想创建一个可以显示所有计算信息的视图,而不是像上面那样运行多个查询。 我希望看法看起来更像这样:

CID   | Year | PaymentsJan | PaymentsFeb | ...
1     | 2015 | 3000.00     | 3000.00     | ...
2     | 2015 | 2000.00     | 2000.00     | ...
3     | 2015 | 5000.00     | 5000.00     | ...
1     | 2014 | 1000.00     | 3000.00     | ...
2     | 2014 | 3000.00     | 4000.00     | ...
3     | 2014 | 2000.00     | 5000.00     | ...

任何人都可以提供有关处理此问题的最佳方法的任何见解吗?

1 个答案:

答案 0 :(得分:0)

您可以使用所需的年份和CID构建一个临时表,然后加入您的查询以便在一个表上完成所有这些操作。许多子查询会很慢,但比手动执行每个查询要好。

create table #Dates
(
controlCID int
,controlYear varchar(4)
)

DECLARE @year int = YEAR( getDate() )
DECLARE @numYears int = 6
DECLARE @numCID int = 5
DECLARE @CIDcounter int

while (@numYears > 0)
BEGIN
    SET @CIDcounter = @numCID

    while (@CIDcounter > 0)
    BEGIN
        insert into #Dates values ( @CIDcounter,  (@year - @numYears + 1))

        SET @CIDcounter = @CIDcounter - 1
    END

    SET @numYears = @numYears -1
END

select controlCID
    ,controlYear
    --,(   SELECT SUM( legacy_reports_payments.AmountPaid ) * -1 AS Payments FROM  legacy_reports_payments
    --WHERE   p.DatePaid >= (controlYear+'-01-01 00:00:00')   AND p.DatePaid < (controlYear+'-02-01 00:00:00')
    --AND p.CID = controlCID) As PaymentsJan,   
    --etc and so on...
 from #Dates 
order by controlYear desc, controlCID 

drop table #Dates

只需使用子查询中表格中的年份和CID,你就应该好了。