Link to home
Start Free TrialLog in
Avatar of RIAS
RIASFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Get total count by Year

Hello,
I have a table with 3 date columns, need to find total records for an year :
User generated image
Example:

ASKER CERTIFIED SOLUTION
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sorry, but the total number of rows for the year 2021 is 9, not 11.

So, please rephrase your question.

Edit: typo.
Avatar of RIAS

ASKER

Sorry, but the total number of rows for the year 2011 is 9, not 11.

So, please rephrase your question.


There is no 2011 present.

Typo, 2021.
Avatar of RIAS

ASKER

It is 11 ste5an, 9 in MOTREF1 and 2 in MOTREF2 , they are highlighted in yellow to avoid confusion. 
There are 11 occurrences in 9 rows.
7 rows where it occurs once per row. 2 rows where it occurs twice.
Thus 9, not 11.
Avatar of RIAS

ASKER

We are not counting rows, we are counting the number of records per year. It is not relating to name. It is just counting years. 
Records is an object oriented or entity oriented concept. You tagged your question as SQL. There are only rows and columns.
Avatar of RIAS

ASKER

I am trying to use this query in Power BI and it does not accept brackets. I receive a error;
Microsoft SQL: Incorrect syntax near the keyword 'with'. Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon. Incorrect syntax near ')'.

Any other way of achieving the same results?

Thanks
you may try this:

select yr, count(yr) cnt
from (
   select year(MOTRef1) yr from yourTable union all
   select year(MOTRef2) yr from yourTable union all
   select year(MOTRef3) yr from yourTable
) cte
group by yr
order by yr

Open in new window


Avatar of RIAS

ASKER

@Ryan, I am posting your solution in a separate question as Power BI needs a simple query without order by and ';'
Avatar of RIAS

ASKER

Thanks, Ryan that worked!
You don't need to scan the table 3 times in order to do this.
Avatar of RIAS

ASKER

Any suggestion? 
Normalize it with CROSS APPLY ( VALUES( ) ).
Avatar of RIAS

ASKER

Can I request to provide an query syntax ?
Thanks ste5an
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RIAS

ASKER

Thanks Ste5an! Will try and be right back.
Avatar of RIAS

ASKER

Thanks, it worked!