I can show you the code for executing a SQL query – it's also in our free book on making trend and historical reports. The actual .NET Framework code is pretty simple, and if you have the SQL Server module it's even easier – just run Invoke-SQL.
You'll need to know how to write a T-SQL query, but that's not really a PowerShell question at that point. The aforementioned book does have some query language examples. There are also tons of online references for SQL queries.