我如何在表中两次显示同一列,但使用sql显示不同的数据?
我有3张桌子tbstu, tbexm, tbscr
tbstu = stucod int PK, stunam var(100)
tbexm = exmcod int PK, exmnam var(100)
tbscr = scrcod int PK, scrsub var(100), scrach int
scrstucod int FK (to table tbstu)
screxmcod int FK (to table tbexm)
qry =
select scrcod, screxmcod, scrstucod, scrsub, scrach, scrach
from tbscr, tbstu, tbexm
where scrstucod = stucod
and screxmcod = exmcod
and stucod = 101
and exmcod = 1001
现在,我希望选择的第二个scrach
显示关于exmcod=1002
和总计列的数据,以对和and进行求和
答案 0 :(得分:0)
如果我理解正确,
使用左联接:
select
tbscr1.scrcod,
tbscr2.scrcod ,
tbscr1.screxmcod,
tbscr2.screxmcod,
tbscr1.scrstucod
tbscr2.scrstucod,
tbscr1.scrsub,
tbscr2.scrsub
tbscr1.scrach,
tbscr2.scrach,
tbscr1.scrach+tbscr2.scrach AS Total
from tbstu,tbexm
left join
tbscr as tbscr1 on tbscr1.scrstucod =tbstu.stucod and tbscr1.screxmcod = tbexm.exmcod and tbstu.stucod = 101 and tbexm.exmcod =1001
left join
tbscr as tbscr2 on tbscr2 .scrstucod =tbstu.stucod and tbscr2 .screxmcod = tbexm.exmcod and tbstu.stucod = 101 and tbexm.exmcod =1002
您也可以尝试:
select scrcod ,
screxmcod,
scrstucod,
scrsub,
scrach,
(select scrach from tbscr ,tbstu,tbexm
where scrstucod =stucod and screxmcod = exmcod and stucod = 101 and exmcod =1002) AS scrach2
from tbscr ,tbstu,tbexm
where scrstucod =stucod and screxmcod = exmcod and stucod = 101 and exmcod =1001
答案 1 :(得分:0)
根据我的理解,我认为您希望为特定学生获得以下知识:
如果正确,您可以执行以下操作:
SELECT
sc1.scrcod, sc1.screxmcod, sc1.scrsub, sc1.scrach,
sc2.scrcod, sc2.screxmcod, sc2.scrsub, sc2.scrach,
COALESCE(sc1.scrach, 0) + COALESCE(sc2.scrach, 0) AS TotalScore
FROM tbstu st
LEFT JOIN tbscr sc1 ON st.stucod = sc1.scrstucod AND sc1.screxmcod = 1001 -- Exam 1 info
LEFT JOIN tbscr sc2 ON st.stucod = sc2.scrstucod AND sc2.screxmcod = 1002 -- Exam 2 info
WHERE st.stucod = 101 -- Only get info for student 101
更新
根据您的评论,您似乎还希望根据科目(scrsub
来划分考试成绩。您可以将此字段添加到您的JOIN
条件中:
SELECT
st.stucod,
sc1.scrsub,
sc1.scrach,
sc2.scrach,
COALESCE(sc1.scrach,0) + COALESCE(sc2.scrach,0) AS TotalScore
FROM tbstu st
LEFT JOIN tbscr sc1 -- Exam 1 info
ON st.stucod = sc1.scrstucod AND sc1.screxmcod = 1001
LEFT JOIN tbscr sc2 -- Exam 2 info
ON st.stucod = sc2.scrstucod AND sc2.screxmcod = 1002 AND sc1.scrsub = sc2.scrsub
WHERE st.stucod = 101 -- Only get info for student 101
按照编码,此查询有一些假设:
scrsub
条目(即每项考试有4行)让我知道它的工作原理。