我需要将月份拉上个月以某种方式动态地显示MONTH(bea_CreatedOn) - 1,因此此报告将自动正确地拉出月份总列数。所以,以下代码中的bea_CreatedOn> ='2015-07-01 00:00:00.000'和bea_CreatedOn< ='2015-07-31 23:59:59.000'部分。
SELECT cdb_Account_ID AS AccountID,
cdb_Database,
ISNULL(TMonthly.MonthlyTotalSent, 0) AS [Monthly Emails],
ISNULL(TYearly.YearlyTotalSent, 0) AS [YTD Emails],
'10000' AS Baseline,
'Monthly' AS [Monthly vs Yearly],
'.01' AS [Rate after Baseline],
CASE
WHEN ISNULL(TMonthly.MonthlyTotalSent, 0) < 10000
THEN 0
ELSE ( ISNULL(TMonthly.MonthlyTotalSent, 0) - 10000 ) * .01
END AS [Billable Amount],
'360' AS Product,
'' AS [Paid -Y/N]
FROM [HVV-CENTRALOPSDB].[Security].[dbo].[sec_ClientDatabase] AS t1
LEFT JOIN (SELECT bea_cdb_GUID,
SUM(bea_D_count) AS MonthlyDelivered,
SUM(bea_B_Count) AS MonthlyBounce,
SUM(bea_D_Count) + SUM(bea_B_count) AS MonthlyTotalSent
FROM [HVV-CENTRALOPSDB].[CentralOps].[dbo].[cop_BlastEmailUsage]
WHERE bea_CreatedOn >= '2015-07-01 00:00:00.000'
AND bea_CreatedOn <= '2015-07-31 23:59:59.000'
GROUP BY bea_cdb_GUID) AS TMonthly
ON tMonthly.bea_cdb_GUID = cdb_GUID
LEFT JOIN (SELECT bea_cdb_GUID,
SUM(bea_D_count) AS YearlyDelivered,
SUM(bea_B_Count) AS YearlyBounce,
SUM(bea_D_Count) + SUM(bea_B_count) AS YearlyTotalSent
FROM [HVV-CENTRALOPSDB].[CentralOps].[dbo].[cop_BlastEmailUsage]
WHERE bea_CreatedOn >= '2015-01-01 00:00:00.000'
AND bea_CreatedOn <= '2015-12-31 23:59:59.000'
GROUP BY bea_cdb_GUID) AS TYearly
ON tYearly.bea_cdb_GUID = cdb_GUID
WHERE cdb_Deleted = 0
AND ( ( cdb_Database NOT LIKE '%Test%'
OR cdb_Database NOT LIKE '%Sample%'
OR cdb_Database NOT LIKE '%VIQ%' )
OR cdb_Database NOT IN ( 'P6_OLP_Impl_20091222', 'P6_OLP_LIBE_20101224', 'P7Test_Aristotle_1_11192013', 'P7Test_Aristotle_1_11202013',
'P6_NA-DBName_20131009', 'P6_NAR_SANDBOX', 'P6_VIQ_ASAP_20140314', 'P6_VIQ_TechSupport_20140314',
'P6_VIQ_BerlinRosen_20140314', 'P6_VIQ_Demo_20140314', '' ) )
AND ISNULL(TYearly.YearlyTotalSent, 0) > 0
答案 0 :(得分:0)
你的例子有7月的日期,但月份的过程是8月。
以下代码段将分别为您提供正在进行的开始日期和月末日期。如果您正在使用Sql Server 2012,那么它可以简化(因此我的问题)。
Declare @StartDate DateTime = Cast(Floor(Cast(DateAdd(Month, -1, GetDate()) As Decimal(12, 5))) - ( Day(DateAdd(Month, -1, GetDate())) - 1 ) As DateTime);
Declare @EndDate DateTime = DateAdd(Month, 1, @StartDate) - 1;
注意,现在你已经说过你了2012年,看看EOMonth功能。
Declare @EndDate Date = EOMonth(DateAdd(Month, -1, GetDate();
Declare @StartDate Date = DateAdd(Day, 1, DateAdd(Month, -1, @EndDate));
在我的手机上使用移动应用程序这样做了,所以无法检查它的100%完美......