How can I query historical data based on the value of specific tags

See my thoughts: Durations for certain tag value - #2 by Transistor and Script about calculate the cumulative downtime - #7 by Transistor.