Mikami was writing nears and everyone else except for Light after he had reveal the truth about everything. However, Near has an ace had his sleeve which is the actual the real Death Note that Mikami had, the real one. While the one that Mikami is a fake one made by Near's subordinate. In truth light should have actual won and successfully killed everyone but Mikami f***ed up But got caughted beforehand, light had to kill off her female accomplice which both he and Mikami wrote the name off, thus making Mikami guilty, thanks to Mello actions. Thus Light didn't know Mikami had also wrote down the female accomplice name.
Light then hurry and try to write Near name down, but was shot 9 time (I made that up..but he did got shot a lot of times) by some kid in the police department. Mikami then stabbed himself (Died later) in order to help Light escape.
Ultimately, Light was killed by Ruk.(As he slowly write Light name in his note book)
I'm missed a few parts in the last episode, but this should explain the whole episode.