[英]Creating an SQL View With Calculations From Multiple Tables
So I have two tables that I need information from. 因此,我有两个表需要我提供信息。 I have a ballot_table(vote CHAR(30), username CHAR(30)) that has the name of the candidate each username voted for. 我有一个ballot_table(vote CHAR(30),用户名CHAR(30)),上面有每个用户名投票的候选人的名字。 I also have another table with a list of the candidates. 我还有一张桌子,上面列出了候选人名单。 I need someway to return the list of candidates with the corresponding amount of times there name appears in ballot_table in the same query. 我需要以某种方式返回候选列表,并在相同的查询中以相同的次数返回名称出现在ballot_table中的名称。 Thanks! 谢谢!
This is a horrible design but here is how you do it: 这是一个可怕的设计,但是您可以按照以下方法进行操作:
select count(*) as votes, vote as [candidate]
from ballot_table
where ucase(vote) in (select ucase(item) from table_with_list_of_candidates)
group by ucase(vote)
a better design would have the list of candidates table include a key and then just have the key in the ballot_table with a varchar for a write in (if needed). 更好的设计是使候选表的列表包含一个键,然后将该键包含在ballot_table中,并使用varchar进行写入(如果需要)。
You can do this with an Outer Join
and a Group By
. 您可以使用Outer Join
和Group By
Outer Join
来执行此操作。 I'm assuming the field name in the candidate
table is Name
. 我假设candidate
表中的字段名称为Name
。
Select c.Name, Count(Distinct b.UserName) Votes
From ballot_table b
Right Join candidate c On c.Name = b.Vote
Group By c.Name
This would only return the total votes for the candidates you have in your Candidate
table. 这只会返回Candidate
表中候选人的总票数。 Any other "write-in" vote wouldn't be included. 任何其他“写入”投票都将不包括在内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.