0

The result will be a table where the original table contents are 450,000 rows (or records) of precinct election results for each statewide race in Texas.

Here's my query the way it is:

select 
 UPPER(county) as TXCounty, Name as Presidential_Candidate, 
 sum(votes) as Votes
from ['2020_General_Election_Returns$']
where name in ('Candidate 1', 'Candidate 2')
group by county, Office, Name
order by County, Office, name

The query results show the county repeated twice, one for candidate 1, the other for candidate 2. Meaning, out of 254 Texas counties, it would return 508 rows instead of 254 because it's duplicating the same county to get the values for candidate 2. Is there a way to create a query where there's two extra columns for candidate 2 and the votes they receive? I'm thinking a nested query would do but I'm not proficient in that area yet. It's a lot cleaner than having the county name repeat for candidate 2.

2
  • 1
    Do you want a solution for SQL Server or MySQL? You've tagged your question with both; please remove the irrelevant tag. Also, consider following these suggestions.
    – mustaccio
    Jul 21, 2022 at 19:55
  • Do you always have exactly two candidates? Jul 21, 2022 at 20:24

1 Answer 1

0

If you always have exactly two candidates you can use conditional aggregation

select 
  UPPER(county) as TXCounty,
  min(case when name = 'Candidate 1' then Name end) as Presidential_Candidate1,
  sum(case when name = 'Candidate 1' then votes end) as Votes1,
  min(case when name = 'Candidate 2' then Name end) as Presidential_Candidate2,
  sum(case when name = 'Candidate 2' then votes end) as Votes2
from ['2020_General_Election_Returns$']
where name in ('Candidate 1', 'Candidate 2')
group by
  county
order by
  county;

Admittedly min(case when name = 'Candidate 1' then Name end) could just as well be 'Candidate 1' but it also allows you to use row-numbering

select 
  UPPER(county) as TXCounty,
  min(case when rn = 1 then Name end) as Presidential_Candidate1,
  sum(case when rn = 1 then votes end) as Votes1,
  min(case when rn = 2 then Name end) as Presidential_Candidate2,
  sum(case when rn = 2 then votes end) as Votes2
from (
    select *,
      row_number() over (partition by county order by Name) as rn
    from ['2020_General_Election_Returns$']
    where name in ('Candidate 1', 'Candidate 2')
) t
group by
  county
order by
  county;
1
  • Thanks, that really helps! I managed to perfect it by removing the two min(case when rn = then Name end) statements. With keeping the sum statements and changing votes1 and votes2 to the names of the two candidates, it's simple and precise. Once, again, thanks a lot! Jul 21, 2022 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.