SQL Server How to combine 3 queries into one? -
i want condense following 3 queries 1 query , out put totals 3 columns. oh , how make don't have declare date. want "know" current date, month, , year.
declare @mydate datetime set @mydate = '2015-01-1' select sum(amount) 'day total' [accounting].[dbo].[handpay] accountingdate>=@mydate , accountingdate<dateadd(day,1,@mydate) select sum(amount) 'month total' [accounting].[dbo].[handpay] accountingdate>=@mydate , accountingdate<dateadd(month,1,@mydate) select sum(amount) 'day total' [accounting].[dbo].[handpay] accountingdate>=@mydate , accountingdate<dateadd(year,1,@mydate)
what best way this? thanks!
thanks super fast responses! solved.
if i'm understanding problem correctly, ought work:
declare @today date = convert(date, getdate()); select [day total] = sum(case when [accountingdate] >= @today , [accountingdate] < dateadd(day, 1, @today) [amount] else 0 end), [month total] = sum(case when [accountingdate] >= @today , [accountingdate] < dateadd(month, 1, @today) [amount] else 0 end), [year total] = sum(case when [accountingdate] >= @today , [accountingdate] < dateadd(year, 1, @today) [amount] else 0 end) [accounting].[dbo].[handpay];
note [month total]
, [year total]
don't give sums of entries occur within current month/year, rather sum of entries occur within month/a year of today's date. i'm not sure if that's want, seems consistent original queries.
update: suggested d stanley below, can simplify bit since know date ranges compose [day total]
, [month total]
sums enclosed entirely within date range composes [year total]
sum. here's might like:
declare @today date = convert(date, getdate()); select [day total] = sum(case when [accountingdate] < dateadd(day, 1, @today) [amount] else 0 end), [month total] = sum(case when [accountingdate] < dateadd(month, 1, @today) [amount] else 0 end), [year total] = sum([amount]) [accounting].[dbo].[handpay] [accountingdate] >= @today , [accountingdate] < dateadd(year, 1, @today);
Comments
Post a Comment