SQL to flatten tables