Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CASE statement with window function

Table

Table

Could someone assist I am looking for a solution to get the counts correct for each store item pair. The first count is easy

COUNT (*) OVER(PARTITION BY store ORDER BY s.deptitemcode DESC) StoreItemSeqNo

However for the 2nd count, I only want the count if the Flag is true for each store item pair if the flag is false then the count should be the previous value if there was no previous value it should be zero.

Refer to table example

like image 917
Keshvir Tugh Avatar asked Oct 17 '25 11:10

Keshvir Tugh


1 Answers

Aggregate functions can instead of * also take an expression. If COUNT(..) is called for an expression and not *, it counts everything except NULL. So, to count according to flag:

COUNT (CASE WHEN flag = 1 THEN flag ELSE NULL END) OVER(PARTITION BY store ORDER BY s.deptitemcode DESC) StoreItemSeqNo
like image 109
kutschkem Avatar answered Oct 20 '25 02:10

kutschkem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!