Show column name as months from past year starting from current_date - sql

I am writing a report that shows the total amount of codes for each month since the past year.
Currently if I just do a count for all of the codes in the past year then my result set will look like this
name | code | total | date
build1 x1 10 04-2013
build1 x50 60 05-2013
build1 x1 80 06-2013
build1 x90 450 07-2013
I was able to transpose all of rows so all of the columns would be the month, with the total below it. My updated results look like this now
name | code | apl | may | jun | jul
build1 x1 10 0 80 0
build1 x50 0 60 0 0
build1 x90 0 0 0 450
The code above are the results i am looking for but what I am wanting to do now is to order everything by the current month and then back one year from that current month.
So if the current month is july then my result set would be ordered like this
name | code | jul | jun | may | apl
build1 x1 0 80 0 10
build1 x50 0 0 60 0
build1 x90 450 0 0 0
The problem I am running in to that that I am using alias's as the month names. And you cannot grab the month from an alias. Also, alias's as far as I know are static so they can't change once you have them set. The only way to get the month as a column name is to extract it from your data set. But when I transpose the rows into column I have to use alias's since I am using case statements to get all of the totals for each month.
EDIT: Sorry, postgresql version is 8.4, here is my query that i have so far
SELECT
pname,
code,
SUM(totaljanurary) AS "Janurary",
SUM(totalfebruary) AS "February",
SUM(totalmarch) AS "March",
SUM(totalapril) AS "April",
SUM(totalmay) AS "May",
SUM(totaljune) AS "June",
SUM(totaljuly) AS "July",
SUM(totalaugust) AS "August",
SUM(totalseptember) AS "September",
SUM(totaloctober) AS "October",
SUM(totalnovember) AS "November",
SUM(totaldecember) AS "December"
FROM(
SELECT
pname,
code,
SUM(case when extract (month FROM checked_date)=01 then total else 0 end) AS totaljanurary,
SUM(case when extract (month FROM checked_date)=02 then total else 0 end) AS totalfebruary,
SUM(case when extract (month FROM checked_date)=03 then total else 0 end) AS totalmarch,
SUM(case when extract (month FROM checked_date)=04 then total else 0 end) AS totalapril,
SUM(case when extract (month FROM checked_date)=05 then total else 0 end) AS totalmay,
SUM(case when extract (month FROM checked_date)=06 then total else 0 end) AS totaljune,
SUM(case when extract (month FROM checked_date)=07 then total else 0 end) AS totaljuly,
SUM(case when extract (month FROM checked_date)=08 then total else 0 end) AS totalaugust,
SUM(case when extract (month FROM checked_date)=09 then total else 0 end) AS totalseptember,
SUM(case when extract (month FROM checked_date)=10 then total else 0 end) AS totaloctober,
SUM(case when extract (month FROM checked_date)=11 then total else 0 end) AS totalnovember,
SUM(case when extract (month FROM checked_date)=12 then total else 0 end) AS totaldecember
FROM (
--START HERE
SELECT
pname,
code,
COUNT(code)AS total,
date_trunc('month',checked_date)::date AS checked_date
FROM table1
AND checked_date >= current_date-365
AND checked_date <= current_date
GROUP BY pname, code, date_trunc('month',checked_date)
)T1
GROUP BY pname, code, date_trunc('month',checked_date)
)T2
GROUP BY pname, code
ORDER BY pname, code

You want crosstab(), provided by the additional module tablefunc.
Assuming "date" is of type date (like it should be).
Other details depend on details you forgot to provide.
SELECT * FROM crosstab(
$$SELECT name, code, to_char("date", 'mon'), total
FROM tbl
WHERE "date" < now()
AND "date" >= now() - interval '1 year'
ORDER BY name, extract(month from now()) DESC$$
,$$VALUES
('dec'::text), ('nov'), ('oct'), ('sep'), ('aug'), ('jul')
, ('jun'), ('may'), ('apr'), ('mar'), ('feb'), ('jan')$$
)
AS ct (name text, code text
, dec int, nov int, oct int, sep int, aug int, jul int
, jun int, may int, apr int, mar int, feb int, jan int);
Refer to this closely related answer for additional instructions:
Sum by month and put months as columns
You shouldn't be using date as identifier, it's a reserved word. I double-quoted it.
You shouldn't be using the non-descriptive name name either.

Related

SQL Select Where date in (Jan and March) but not in Feb

I have a table like this in SQL called Balance
+----+-----------+-------+------+
| id | accountId | Date | Type |
+----+-----------+-------+------+
| PK | FK | Date | Int |
+----+-----------+-------+------+
I need to find the accountIds that has balance entries in January and March, but not in Febuary.
Only in 2018 and Type should be 2.
How would I go about writing my sql select statement?
Thanks
Edit:
What's I've done so far:
Selecting rows that either in Jan OR March is not a problem for me.
SELECT AccountId, Date FROM Balance
WHERE Month(Date) in (1,3) AND YEAR(Date) = 2018 AND Type =2
ORDER BY AccountId, Date
But if an AccountId has a single entry, say in January, then this will be included. And that's not what I want.
Only if an Account has entries in both Jan and March, and not in Feb is it interesting.
I suspect Group BY and HAVING are keys here, but I'm unsure how to proceed
I would do this using aggregation:
select b.accountid
from balance b
where date >= '2018-01-01' and date < '2019-01-01'
group by b.accountid
having sum(case when month(date) = 1 then 1 else 0 end) > 0 and -- has january
sum(case when month(date) = 3 then 1 else 0 end) > 0 and -- has march
sum(case when month(date) = 2 then 1 else 0 end) = 0 -- does not have february

Teradata - Split date range into month columns with day count

I need to split different date ranges over a quarter period into month columns with only the days actually used in that month. Each record (range) would be different.
Example:
Table
Record_ID Start_Date End_Date
1 10/27 11/30
2 11/30 12/14
3 12/14 12/31
Range 1 = 10/5 to 12/14
Range 2 = 11/20 to 12/31
Range 3 = 10/28 to 12/2
Output:
Range 1
Oct Nov Dec
27 30 14
Similar to #ULick's answer using sys_calendar.calendar, but a little more succinct:
CREATE VOLATILE MULTISET TABLE datetest (record_id int, start_date date, end_date date) ON COMMIT PRESERVE ROWS;
INSERT INTO datetest VALUES (1, '2017-10-05', '2017-12-14');
INSERT INTO datetest VALUES (2, '2017-11-20','2017-12-31');
SELECT record_id,
SUM(CASE WHEN month_of_year = 10 THEN 1 ELSE 0 END) as October,
SUM(CASE WHEN month_of_year = 11 THEN 1 ELSE 0 END) as November,
SUM(CASE WHEN month_of_year = 12 THEN 1 ELSE 0 END) as December
FROM datetest
INNER JOIN sys_calendar.calendar cal
ON cal.calendar_date BETWEEN start_date and end_date
GROUP BY record_id;
DROP TABLE datetest;
Because Quarter was mentioned in the question (I'm not sure how it relates here) there is also quarter_of_year and month_of_quarter available in the sys_calendar to slice and dice this even further.
Also, if you are on 16.00+ There is PIVOT functionality which may help get rid of the CASE statements here.
First join with the calendar to get all the dates within the range and get the number of days per each month (incl. full month, not mentioned in Start_Date and End_Date).
Then sum up each month in a column per Range.
create table SplitDateRange ( Range bigint, Start_Date date, End_Date date );
insert into SplitDateRange values ( 1, '2018-10-05', '2018-12-14' );
insert into SplitDateRange values ( 2, '2018-11-20', '2018-12-31' );
insert into SplitDateRange values ( 3, '2018-10-28', '2018-12-02' );
select
Range
, sum(case when mon = 10 then days else 0 end) as "Oct"
, sum(case when mon = 11 then days else 0 end) as "Nov"
, sum(case when mon = 12 then days else 0 end) as "Dec"
from (
select
Range
, extract(MONTH from C.calendar_date) as mon
, max(C.calendar_date) - min(calendar_date) +1 as days
from Sys_Calendar.CALENDAR as C
inner join SplitDateRange as DR
on C.calendar_date between DR.Start_Date and DR.End_Date
group by 1,2
) A
group by Range
order by Range
;
Different approach, avoids the cross join to the calendar by applying Teradata Expand On feature for creating time series. More text, but should be more efficient for larger tables/ranges:
SELECT record_id,
Sum(CASE WHEN mth = 10 THEN days_in_month ELSE 0 END) AS October,
Sum(CASE WHEN mth = 11 THEN days_in_month ELSE 0 END) AS November,
Sum(CASE WHEN mth = 12 THEN days_in_month ELSE 0 END) AS December
FROM
( -- this Derived Table simply avoids repeating then EXTRACT/INTERVAL calculations (can't be done directly in the nested Select)
SELECT record_id,
Extract(MONTH From Begin(expanded_pd)) AS mth,
Cast((INTERVAL( base_pd P_INTERSECT expanded_pd) DAY) AS INT) AS days_in_month
FROM
(
SELECT record_id,
PERIOD(start_date, end_date+1) AS base_pd,
expanded_pd
FROM datetest
-- creates one row per month
EXPAND ON base_pd AS expanded_pd BY ANCHOR PERIOD Month_Begin
) AS dt
) AS dt
GROUP BY 1

How to subtract result of 2 queries grouped by a field

I have a table in this form:
id year type amount
1 2015 in 10
2 2015 out 5
3 2016 in 20
4 2016 out 1
...
The followin query will give me the sum of the amount of type = 'in' grouped by year:
SELECT year, sum(amount)
FROM table
WHERE type = in
GROUP BY year
How am I going to get the following result?
year sum(in) sum(out) "in-out"
2015 10 5 5
2016 20 1 19
sum(in) is the sum of the 'amount' where type='in'.
Use a CASE statement to handle the values of type.
SELECT year,
SUM(CASE WHEN type = 'in' THEN amount ELSE 0 END) AS sum_in,
SUM(CASE WHEN type = 'out' THEN amount ELSE 0 END) AS sum_out,
SUM(CASE WHEN type = 'in' THEN amount ELSE -amount END) AS in_out
FROM table
GROUP BY year;

How to maintain a running balance in a month wise report

SELECT *
FROM
(SELECT
YEAR (DateOfTransaction) AS year,
LEFT(DATENAME(MONTH, DateOfTransaction), 3) AS month,
SUM(CASE WHEN TransTypeName LIKE 'credit%' THEN amount ELSE 0 END) -
SUM(CASE WHEN TransTypeName LIKE 'Debit%' THEN amount ELSE 0 END) AS Balance
FROM
.............) AS t
PIVOT (SUM(balance) FOR month IN (jan, feb, march, ...., Dec)) AS pvt
This query returns a month-wise report account balance. I want a result is running balance.
Example:
January month I credit 5000, February month I credit 2000
My query result is
year jan feb march...dec
2014 5000 2000 null ..null
I want a result like this:
year jan feb march...dec
2014 5000 7000 null ..null
(5000+2000)
Try this
SELECT year,Jan = Jan, Feb = isnull(Jan,0)+isnull(Feb,0),....
FROM
(SELECT
YEAR (DateOfTransaction) AS year,
LEFT(DATENAME(MONTH, DateOfTransaction), 3) AS month,
SUM(CASE WHEN TransTypeName LIKE 'credit%' THEN amount ELSE 0 END) -
SUM(CASE WHEN TransTypeName LIKE 'Debit%' THEN amount ELSE 0 END) AS Balance
FROM
.............) AS t
PIVOT (SUM(balance) FOR month IN (jan, feb, march, ...., Dec)) AS pvt)t
Or you can simply add a temp table which stores numbers from 1 to 12
inner join #temp on n>=datepart(mm,DateofTransaction) group by year(transaction), n

SQL Table UPDATE by row with days per month

SQL Server 2005:
I'm attempting to create a table that looks like this:
JAN | FEB | March .......Dec | YTD
Total Volume:
Days in Month:
Gallons per day AVG:
Three rows with description on left, 13 columns (one for each month and year to date total).
I know how to populate the total volume per month. What would I use for days per month and average? I'd like the days per month to show either the complete number of days if it is a past month or current completed days if its the current month.
You are pivoting the data, so you want the results in columns. You can do this by using direct calculation. Here is an example for the first three months:
select 'Days In Month' as col1,
(case when month(getdate()) < 1 then 0
when month(getdate()) = 1 then day(getdate())
else 31
end) as Jan,
(case when month(getdate()) < 2 then 0
when month(getdate()) = 2 then day(getdate())
when year(getdate()) % 4 = 0 then 29
else 28
end) as Feb,
(case when month(getdate()) < 3 then 0
when month(getdate()) = 3 then day(getdate())
else 31
end) as Mar,