我们有一个表,用于从Excel文件中导入数据。
我正在从该表创建视图,将表本身连接起来,并添加一个rownumber列。不幸的是,当我运行sql语句时,又多了两行,我无法弄清楚如何摆脱它们,或者是否有更好的解决方案来添加行号/联接表。
原始表中的每个候选行都有一行yes和no。我试图加入他们的行列,所以在选区/竞赛的同一行中没有出现。
SELECT CAST(ROW_NUMBER() OVER (ORDER BY
(SELECT 1)) AS INT) AS ID, t .*
FROM (SELECT DISTINCT
a.PRECINCT_NAME,
a.CONTEST_FULL_NAME,
CAST(a.BALLOT_CAST AS INT) AS 'BALLOT_CAST',
a.CANDIDATE_FULL_NAME AS 'CANDIDATE_1',
a.PARTY_CODE AS 'PARTY_CODE_1',
CAST(a.VOTE_COUNT AS INT) AS 'VOTECOUNT_1',
b.CANDIDATE_FULL_NAME AS 'CANDIDATE_2',
b.PARTY_CODE AS 'PARTY_CODE_2',
CAST(b.VOTE_COUNT AS INT) AS 'VOTECOUNT_2'
FROM dbo.Election_Special a
JOIN dbo.Election_Special b
ON a.PRECINCT_NAME = b.PRECINCT_NAME
WHERE
(a.CANDIDATE_FULL_NAME = 'Yes') AND (b.CANDIDATE_FULL_NAME = 'No')
) AS t
Actual Output:
PRECINCT NAME | CONTEST FULL NAME | CANDIDATE 1 | VOTE 1 | CANDIDATE 2 | VOTE 2
PRECINCT 1 | CONTEST 1 | YES | 3 | NO | 3
PRECINCT 2 | CONTEST 2 | YES | 6 | NO | 4
PRECINCT 3 | CONTEST 3 | YES | 7 | NO | 5
PRECINCT 4 | CONTEST 1 | YES | 1 | NO | 7
PRECINCT 4 | CONTEST 2 | YES | 6 | NO | 1
PRECINCT 4 | CONTEST 1 | YES | 0 | NO | 0
PRECINCT 4 | CONTEST 2 | YES | 0 | NO | 0
PRECINCT 5 | CONTEST 3 | YES | 3 | NO | 4
Expected OutPut
PRECINCT NAME | CONTEST FULL NAME | CANDIDATE 1 | VOTE 1 | CANDIDATE 2 | VOTE 2
PRECINCT 1 | CONTEST 1 | YES | 3 | NO | 3
PRECINCT 2 | CONTEST 2 | YES | 6 | NO | 4
PRECINCT 3 | CONTEST 3 | YES | 7 | NO | 5
PRECINCT 4 | CONTEST 1 | YES | 1 | NO | 7
PRECINCT 4 | CONTEST 2 | YES | 6 | NO | 1
PRECINCT 5 | CONTEST 3 | YES | 3 | NO | 4
答案 0 :(得分:1)
此刻,您正在“爆炸”您的数据。 1行变成2。
您需要弄清楚表的“自然键”是什么-即每个组合给出1行的列。
我认为这是精确名称和竞赛全名 因此您可以通过/拥有...来与一个小组进行测试...
select PRECINCT NAME , CONTEST FULL NAME
from election_special
group by
PRECINCT NAME , CONTEST FULL NAME
having count(*) > 1
如果此记录返回0条记录,则说明您已经全部设置好了,您只需将此列添加到自连接中即可
例如:
ON a.PRECINCT_NAME = b.PRECINCT_NAME
and a.CONTEST_FULL_NAME = b.CONTEST_FULL_NAME