The melody of a song, that is being played on top of a chord, can be any of the notes of the chord (but is not limited to those1 !).
The part you mentioned has G as a chord. The notes that consist the G chord are G,B,D; you can play any of those notes in the melody and they will sound nice. Τhe order in which they are played doesn't affect the harmony in the least. You can play the notes in any way you want (you can also omit some of them, like the last bar of your example).
The given melody starts off with the third note of the chord, D, then goes to G and then to B. It plays all the three notes of the G chord.
1 For example, you can see on the F chord that there are the notes E & D that don't belong to the chord. These notes are used to pass from one note of the chord to some other. They are called Passing Tones.