cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
ThomasdotM
New Member

Count of occurrence and sum in a sharepoint list

Hi all,

 

Very rookie question here as I'm not even sure it's possible to build this flow.

I have a sharepoint list where the inputs are the leaves of the employees.

The sherepoint list is fed through power app.

 

Once a new item is created or modified, i want two operations to happen on this item:

- Count the number of time one person have appeared in the list for the last 365 days from the date of return (Occurrences last 12 months)

- Sums up the durations fot the last 12 months from the date of return (Sum durations last 12 months)

 

Here is a table representing the datas, last two colomns are the one i try to calculate through a power automate workflow:

IDNameDate returnDurationOccurrences last 12 monthsSum durations last 12 months
1James12/12/2022  414
2Michael01/01/2023  515
3James09/01/2023  327
4James04/02/2023  5312
5James03/02/2024  328
6James09/01/2025  225

 

Not sure if helps, but here are the Excel formulas corresponding to the operation:

-Occurrences last 12 months = =COUNTIFS([Name];[@Name];[Date return];">="&([@[Date return]]-365);[Date return];"<="&[@[Date return]])

-Sum durations last 12 months =SUMIFS([Duration];[Name];[@Name];[Date return];">="&([@[Date return]]-365);[Date return];"<="&[@[Date return]])

 

Thanks a lot for any feedback 🙂

Thomas.

1 ACCEPTED SOLUTION

Accepted Solutions
grantjenkins
Super User
Super User

That was fun 🙂. Hopefully this is what you're looking for.

 

For this example, I have the following list.

grantjenkins_0-1676036498446.png

 

Below is the full flow. I'll go into each of the actions.

grantjenkins_1-1676036719166.png

 

When an item is created or modified will is fairly straightforward.

grantjenkins_2-1676036769453.png

 

Because our trigger fires when an item is modified, and we are modifying our items within the flow, we would end up with an infinite loop (our flow would continue to run over and over and over again). To avoid this, we can check the previous version of the item that was modified and check if the Date Return, or Duration has changed, and only continue if one of them have. And if it was a new item just created, it wouldn't have a previous version, so we need to cater for that too.

 

Get changes for an item or a file (properties only) will retrieve the previous version of the item and provide us with dynamic properties to check if fields have changed.

grantjenkins_3-1676037031674.png

 

Condition checks to see if it's a new item that was created (Version Number is 1.0), or if any of the fields (Date Return or Duration) have changed. This will ensure the flow doesn't get into an infinite loop. It uses the following expression to get the version number.

 

float(triggerOutputs()?['body/{VersionNumber}'])

 

grantjenkins_9-1676038036785.png

 

If any of the conditions return true, we go into the Yes branch and continue on with our flow.

 

Get items Current and Future will return all items where the Title is equal to the Title of the item we created/modified and has an ID greater than or equal to the ID of the item we created/modified. This will cater for changes made to previous entries where we need to recalculate all entries after that one. We also sort by ID, so we update the earliest items first since the later items use the data from the previous items in their calculations.

grantjenkins_5-1676037560340.png

 

Apply to each iterates over each of the items from Get items Current and Future.

grantjenkins_6-1676037618252.png

 

For each of the items, we retrieve the data 12 months from the Date Return up until the Date Return. The expression used is:

 

Title eq '@{triggerOutputs()?['body/Title']}' and DateReturn ge '@{addToTime(item()?['DateReturn'], -12, 'Month')}' and DateReturn le '@{items('Apply_to_each')?['DateReturn']}'

 

grantjenkins_7-1676037730322.png

 

Update item uses the ID and Title from Get items Current and Future and uses the following expressions to calculate the Occurrences and Sum. Note that Sum is using XPath so we can sum across the rows easily.

 

//Occurrences
length(outputs('Get_items_Current_and_Past')?['body/value'])

//Sum
xpath(xml(json(concat('{"root": { value:', outputs('Get_items_Current_and_Past')?['body/value'], '}}'))), 'sum(//root/value/Duration/text())')

 

grantjenkins_8-1676037885105.png

 

This should cater for new items and any items that have the Date Return or Duration updated anywhere in the list.


----------------------------------------------------------------------
If I've answered your question, please mark the post as Solved.
If you like my response, please consider giving it a Thumbs Up.


----------------------------------------------------------------------
If I've answered your question, please mark the post as Solved.
If you like my response, please consider giving it a Thumbs Up.

View solution in original post

7 REPLIES 7
grantjenkins
Super User
Super User

Sounds challenging, but definitely doable. I'll see what I can come up with 🙂

 

A few questions.

  1. Is your Name column data type a Single line of text or Person?
  2. Approx. how many items are in your list - and how many would there be within the next 5 years?
  3. What happens if you modify an earlier item for a person? Would you want to recalculate all occurrences of that person from that point forward since the later calculations may now be incorrect? Or would you only ever modify the latest item for a person?
    • Example - I add some leave and it performs the calculations. Then I edit a previous entry for that person - I'd need to recalculate for the item I just modified, plus the latest item since that is calculated on previous items.

----------------------------------------------------------------------
If I've answered your question, please mark the post as Solved.
If you like my response, please consider giving it a Thumbs Up.
grantjenkins
Super User
Super User

That was fun 🙂. Hopefully this is what you're looking for.

 

For this example, I have the following list.

grantjenkins_0-1676036498446.png

 

Below is the full flow. I'll go into each of the actions.

grantjenkins_1-1676036719166.png

 

When an item is created or modified will is fairly straightforward.

grantjenkins_2-1676036769453.png

 

Because our trigger fires when an item is modified, and we are modifying our items within the flow, we would end up with an infinite loop (our flow would continue to run over and over and over again). To avoid this, we can check the previous version of the item that was modified and check if the Date Return, or Duration has changed, and only continue if one of them have. And if it was a new item just created, it wouldn't have a previous version, so we need to cater for that too.

 

Get changes for an item or a file (properties only) will retrieve the previous version of the item and provide us with dynamic properties to check if fields have changed.

grantjenkins_3-1676037031674.png

 

Condition checks to see if it's a new item that was created (Version Number is 1.0), or if any of the fields (Date Return or Duration) have changed. This will ensure the flow doesn't get into an infinite loop. It uses the following expression to get the version number.

 

float(triggerOutputs()?['body/{VersionNumber}'])

 

grantjenkins_9-1676038036785.png

 

If any of the conditions return true, we go into the Yes branch and continue on with our flow.

 

Get items Current and Future will return all items where the Title is equal to the Title of the item we created/modified and has an ID greater than or equal to the ID of the item we created/modified. This will cater for changes made to previous entries where we need to recalculate all entries after that one. We also sort by ID, so we update the earliest items first since the later items use the data from the previous items in their calculations.

grantjenkins_5-1676037560340.png

 

Apply to each iterates over each of the items from Get items Current and Future.

grantjenkins_6-1676037618252.png

 

For each of the items, we retrieve the data 12 months from the Date Return up until the Date Return. The expression used is:

 

Title eq '@{triggerOutputs()?['body/Title']}' and DateReturn ge '@{addToTime(item()?['DateReturn'], -12, 'Month')}' and DateReturn le '@{items('Apply_to_each')?['DateReturn']}'

 

grantjenkins_7-1676037730322.png

 

Update item uses the ID and Title from Get items Current and Future and uses the following expressions to calculate the Occurrences and Sum. Note that Sum is using XPath so we can sum across the rows easily.

 

//Occurrences
length(outputs('Get_items_Current_and_Past')?['body/value'])

//Sum
xpath(xml(json(concat('{"root": { value:', outputs('Get_items_Current_and_Past')?['body/value'], '}}'))), 'sum(//root/value/Duration/text())')

 

grantjenkins_8-1676037885105.png

 

This should cater for new items and any items that have the Date Return or Duration updated anywhere in the list.


----------------------------------------------------------------------
If I've answered your question, please mark the post as Solved.
If you like my response, please consider giving it a Thumbs Up.


----------------------------------------------------------------------
If I've answered your question, please mark the post as Solved.
If you like my response, please consider giving it a Thumbs Up.
ThomasdotM
New Member

Hi @grantjenkins 

 

What a legend, never thought i would get such a comprehensive and detailed answer !

 

I will give it a try as soon as possible and will let you know 🙂

 

To answer your previous questions:

  1. Column "Name" is a person column but i figured out earlier how to transform it in text.
  2. There will be around 750 items per year, so around 4000 items in 5 years. I will probably create an auto-archive every year to keep the list light
  3. In a perfect world, the other lines would update when one line is modified. I see you have integrated this option in your flow, if it doesn't make the flow too heavy that's an incredible feature, else I can maybe try to allow only the modification of the lastest dates of the list (not sure if this option exists in power app 😁).  

Not sure how to thank you but this is an incredible help !

 

Have a good weekend,

Thomas.

I'll try it with a Person column instead of a Single line of text column and see how it goes - I'm fairly sure it won't affect the flow as it is. If you wanted to use a Person column, what would you put in the Title field since it's a required field?

 

Given the number of items in the list, I'd also suggest modifying the Get items Current and Future and Get items Current and Past so they're using Pagination and have a Threshold set which will allow for more items to be returned. Threshold would be set to a number greater than the number of items you expect your list to have.

 

grantjenkins_0-1676073609474.png

 

grantjenkins_3-1676073823600.png

 

And setting the Top Count to 5000 will return your items in batches of 5000 at a time.

grantjenkins_2-1676073698289.png

 

You would do this for both of the Get items actions.


----------------------------------------------------------------------
If I've answered your question, please mark the post as Solved.
If you like my response, please consider giving it a Thumbs Up.
ThomasdotM
New Member

Hi @grantjenkins 

 

Thanks again for all your details.

 

I did apply everything above and the occurrence is working just fine.

 

However the sum formula always return 0.

I'm not sure if it comes from that but whenever I add the update item action and choose ID from "Get items current and past", it automatically creates an "apply to each" action:

ThomasdotM_0-1676457308017.png

I tried many different configurations (like using the datas from "get items current and future") but the issue is still there.

 

When i do a test run, the previsous steps seem to retrieve the rigth data, is it possible that it comes from the formula ?

 

 

And to anwser your question about the title field, I'm not really sure how to efficently use it so i just increment it for every new line created in the sharepoint list.

 

Thanks again for everything,

Thomas.

 

@ThomasdotM Sorry, I made a mistake when describing what you use for the ID and Title in Update item. The ID and Title should be coming from Get items Current and Future which wouldn't add another loop. I've updated my original post to reflect the changes.

 

grantjenkins_0-1677376740453.png

 

Let me know if this change resolves the issue.


----------------------------------------------------------------------
If I've answered your question, please mark the post as Solved.
If you like my response, please consider giving it a Thumbs Up.
ThomasdotM
New Member

Hi @grantjenkins 

 

This definitely fixed the additionnal loop 🙂

 

However I'm still unable to calculate the sum of durations.

 

It's very mysterious for me because the step "get item current and past" do recover the good shortilisted items, including "Dur_x00e9_eabsence":5.0 (and the followng ones) which is my field name equivalent to duration in your case

 

The sum of duration formula then becomes 

 

xpath(xml(json(concat('{"root": { value:', outputs('Get_items_Current_and_Past')?['body/value'], '}}'))), 'sum(//root/value/Dur_x00e9_eabsence/text())')

 

 

But it always return 0 in the sum of duration field.

I'm sure I'm doing something wrong somewhere but I tried so many alternatives and setting I'm a bit lost on that.

 

 

And there is also another "side effect", whenever an early item is modified and trigger the flow, it will erases the results of the occurrences of the later lines.

 

 

So to be honest it's a bit out of my range and I will probably remove these calculations so the table stays simple and future maintenance of the system can be performed.

There is still the possibility to extract the datas to an excel spreadsheet and do a simple caculation.

 

Anyway, thanks a lot for your time, learnt a lot about the different features and the limits of the sharepoint lists through the differen tests.

Will probably get back to it in the future when I have time to play with the solution 🙂

Helpful resources

Announcements

Power Platform Connections Ep 15 | L. Baybutt | Thursday, 1 June 2023

Episode Fifteen of Power Platform Connections sees David Warner and Hugo Bernier talk to Microsoft MVP Lewis Baybutt aka Low Code Lewis, alongside the latest news and community blogs.   Use the hashtag #PowerPlatformConnects on social media for a chance to have your work featured on the show.        Action requested: Feel free to provide feedback on how we can make our community more inclusive and diverse.  This episode premiers live on our YouTube at 12pm PST on Thursday 1st June 2023.  Video series available at Power Platform Community YouTube channel.    Upcoming events:  European Power Platform conference – Jun. 20-22nd - Dublin Microsoft Power Platform Conference – Oct. 3-5th - Las Vegas  Join our Communities:  Power Apps Community Power Automate Community Power Virtual Agents Community Power Pages Community  If you’d like to hear from a specific community member in an upcoming recording and/or have specific questions for the Power Platform Connections team, please let us know. We will do our best to address all your requests or questions.  Action requested: Feel free to provide feedback on how we can make our community more inclusive and diverse.  This episode premiers live on our YouTube at 12pm PST on Thursday 1st June 2023.  Video series available at Power Platform Community YouTube channel.    Upcoming events:  European Power Platform conference – Jun. 20-22nd - Dublin Microsoft Power Platform Conference – Oct. 3-5th - Las Vegas  Join our Communities:  Power Apps Community Power Automate Community Power Virtual Agents Community Power Pages Community  If you’d like to hear from a specific community member in an upcoming recording and/or have specific questions for the Power Platform Connections team, please let us know. We will do our best to address all your requests or questions. 

May 2023 Community Newsletter and Upcoming Events

Welcome to our May 2023 Community Newsletter, where we'll be highlighting the latest news, releases, upcoming events, and the great work of our members inside the Biz Apps communities. If you're new to this LinkedIn group, be sure to subscribe here in the News & Announcements to stay up to date with the latest news from our ever-growing membership network who "changed the way they thought about code".         LATEST NEWS "Mondays at Microsoft" LIVE on LinkedIn - 8am PST - Monday 15th May  - Grab your Monday morning coffee and come join Principal Program Managers Heather Cook and Karuana Gatimu for the premiere episode of "Mondays at Microsoft"! This show will kick off the launch of the new Microsoft Community LinkedIn channel and cover a whole host of hot topics from across the #PowerPlatform, #ModernWork, #Dynamics365, #AI, and everything in-between. Just click the image below to register and come join the team LIVE on Monday 15th May 2023 at 8am PST. Hope to see you there!     Executive Keynote | Microsoft Customer Success Day CVP for Business Applications & Platform, Charles Lamanna, shares the latest #BusinessApplications product enhancements and updates to help customers achieve their business outcomes.         S01E13 Power Platform Connections - 12pm PST - Thursday 11th May Episode Thirteen of Power Platform Connections sees Hugo Bernier take a deep dive into the mind of co-host David Warner II, alongside the reviewing the great work of Dennis Goedegebuure, Keith Atherton, Michael Megel, Cat Schneider, and more. Click below to subscribe and get notified, with David and Hugo LIVE in the YouTube chat from 12pm PST. And use the hashtag #PowerPlatformConnects on social media for a chance to have your work featured on the show.         UPCOMING EVENTS   European Power Platform Conference - early bird ticket sale ends! The European Power Platform Conference early bird ticket sale ends on Friday 12th May 2023! #EPPC23 brings together the Microsoft Power Platform Communities for three days of unrivaled days in-person learning, connections and inspiration, featuring three inspirational keynotes, six expert full-day tutorials, and over eighty-five specialist sessions, with guest speakers including April Dunnam, Dona Sarkar, Ilya Fainberg, Janet Robb, Daniel Laskewitz, Rui Santos, Jens Christian Schrøder, Marco Rocca, and many more. Deep dive into the latest product advancements as you hear from some of the brightest minds in the #PowerApps space. Click here to book your ticket today and save!      DynamicMinds Conference - Slovenia - 22-24th May 2023 It's not long now until the DynamicsMinds Conference, which takes place in Slovenia on 22nd - 24th May, 2023 - where brilliant minds meet, mingle & share! This great Power Platform and Dynamics 365 Conference features a whole host of amazing speakers, including the likes of Georg Glantschnig, Dona Sarkar, Tommy Skaue, Monique Hayward, Aleksandar Totovic, Rachel Profitt, Aurélien CLERE, Ana Inés Urrutia de Souza, Luca Pellegrini, Bostjan Golob, Shannon Mullins, Elena Baeva, Ivan Ficko, Guro Faller, Vivian Voss, Andrew Bibby, Tricia Sinclair, Roger Gilchrist, Sara Lagerquist, Steve Mordue, and many more. Click here: DynamicsMinds Conference for more info on what is sure an amazing community conference covering all aspects of Power Platform and beyond.    Days of Knowledge Conference in Denmark - 1-2nd June 2023 Check out 'Days of Knowledge', a Directions 4 Partners conference on 1st-2nd June in Odense, Denmark, which focuses on educating employees, sharing knowledge and upgrading Business Central professionals. This fantastic two-day conference offers a combination of training sessions and workshops - all with Business Central and related products as the main topic. There's a great list of industry experts sharing their knowledge, including Iona V., Bert Verbeek, Liza Juhlin, Douglas Romão, Carolina Edvinsson, Kim Dalsgaard Christensen, Inga Sartauskaite, Peik Bech-Andersen, Shannon Mullins, James Crowter, Mona Borksted Nielsen, Renato Fajdiga, Vivian Voss, Sven Noomen, Paulien Buskens, Andri Már Helgason, Kayleen Hannigan, Freddy Kristiansen, Signe Agerbo, Luc van Vugt, and many more. If you want to meet industry experts, gain an advantage in the SMB-market, and acquire new knowledge about Microsoft Dynamics Business Central, click here Days of Knowledge Conference in Denmark to buy your ticket today!   COMMUNITY HIGHLIGHTS Check out our top Super and Community Users reaching new levels! These hardworking members are posting, answering questions, kudos, and providing top solutions in their communities.   Power Apps:  Super Users: @WarrenBelz, @LaurensM  @BCBuizer  Community Users:  @Amik@ @mmollet, @Cr1t    Power Automate:  Super Users: @Expiscornovus , @grantjenkins, @abm  Community Users: @Nived_Nambiar, @ManishSolanki    Power Virtual Agents:  Super Users: @Pstork1, @Expiscornovus  Community Users: @JoseA, @fernandosilva, @angerfire1213    Power Pages: Super Users: @ragavanrajan  Community Users: @Fubar, @Madhankumar_L,@gospa  LATEST COMMUNITY BLOG ARTICLES  Power Apps Community Blog  Power Automate Community Blog  Power Virtual Agents Community Blog  Power Pages Community Blog  Check out 'Using the Community' for more helpful tips and information:  Power Apps , Power Automate, Power Virtual Agents, Power Pages 

Announcing | Super Users - 2023 Season 1

Super Users – 2023 Season 1    We are excited to kick off the Power Users Super User Program for 2023 - Season 1.  The Power Platform Super Users have done an amazing job in keeping the Power Platform communities helpful, accurate and responsive. We would like to send these amazing folks a big THANK YOU for their efforts.      Super User Season 1 | Contributions July 1, 2022 – December 31, 2022  Super User Season 2 | Contributions January 1, 2023 – June 30, 2023    Curious what a Super User is? Super Users are especially active community members who are eager to help others with their community questions. There are 2 Super User seasons in a year, and we monitor the community for new potential Super Users at the end of each season. Super Users are recognized in the community with both a rank name and icon next to their username, and a seasonal badge on their profile.  Power Apps  Power Automate  Power Virtual Agents  Power Pages  Pstork1*  Pstork1*  Pstork1*  OliverRodrigues  BCBuizer  Expiscornovus*  Expiscornovus*  ragavanrajan  AhmedSalih  grantjenkins  renatoromao    Mira_Ghaly*  Mira_Ghaly*      Sundeep_Malik*  Sundeep_Malik*      SudeepGhatakNZ*  SudeepGhatakNZ*      StretchFredrik*  StretchFredrik*      365-Assist*  365-Assist*      cha_cha  ekarim2020      timl  Hardesh15      iAm_ManCat  annajhaveri      SebS  Rhiassuring      LaurensM  abm      TheRobRush  Ankesh_49      WiZey  lbendlin      Nogueira1306  Kaif_Siddique      victorcp  RobElliott      dpoggemann  srduval      SBax  CFernandes      Roverandom  schwibach      Akser  CraigStewart      PowerRanger  MichaelAnnis      subsguts  David_MA      EricRegnier  edgonzales      zmansuri  GeorgiosG      ChrisPiasecki  ryule      AmDev  fchopo      phipps0218  tom_riha      theapurva  takolota     Akash17  momlo     BCLS776  Shuvam-rpa     rampprakash  ScottShearer     Rusk  ChristianAbata     cchannon  Koen5     a33ik  Heartholme     AaronKnox  okeks      Matren  David_MA     Alex_10        Jeff_Thorpe        poweractivate        Ramole        DianaBirkelbach        DavidZoon        AJ_Z        PriyankaGeethik        BrianS        StalinPonnusamy        HamidBee        CNT        Anonymous_Hippo        Anchov        KeithAtherton        alaabitar        Tolu_Victor        KRider        sperry1625        IPC_ahaas      zuurg    rubin_boer   cwebb365   Dorrinda   G1124   Gabibalaban   Manan-Malhotra   jcfDaniel   WarrenBelz   Waegemma   drrickryp   GuidoPreite   metsshan    If an * is at the end of a user's name this means they are a Multi Super User, in more than one community. Please note this is not the final list, as we are pending a few acceptances.  Once they are received the list will be updated. 

Check out the new Power Platform Communities Front Door Experience!

We are excited to share the ‘Power Platform Communities Front Door’ experience with you!   Front Door brings together content from all the Power Platform communities into a single place for our community members, customers and low-code, no-code enthusiasts to learn, share and engage with peers, advocates, community program managers and our product team members. There are a host of features and new capabilities now available on Power Platform Communities Front Door to make content more discoverable for all power product community users which includes ForumsUser GroupsEventsCommunity highlightsCommunity by numbersLinks to all communities Users can see top discussions from across all the Power Platform communities and easily navigate to the latest or trending posts for further interaction. Additionally, they can filter to individual products as well.   Users can filter and browse the user group events from all power platform products with feature parity to existing community user group experience and added filtering capabilities.     Users can now explore user groups on the Power Platform Front Door landing page with capability to view all products in Power Platform.      Explore Power Platform Communities Front Door today. Visit Power Platform Community Front door to easily navigate to the different product communities, view a roll up of user groups, events and forums.

Microsoft Power Platform Conference | Registration Open | Oct. 3-5 2023

We are so excited to see you for the Microsoft Power Platform Conference in Las Vegas October 3-5 2023! But first, let's take a look back at some fun moments and the best community in tech from MPPC 2022 in Orlando, Florida.   Featuring guest speakers such as Charles Lamanna, Heather Cook, Julie Strauss, Nirav Shah, Ryan Cunningham, Sangya Singh, Stephen Siciliano, Hugo Bernier and many more.   Register today: https://www.powerplatformconf.com/   

Users online (2,515)