如何链接以下2个表以获得SQL Server中显示的结果?`

时间:2011-01-29 04:46:46

标签: sql-server sql-server-2005

访问

LoginID, StaffName, qno, trackno, tmstamp
1,       James,     1001, 1,      01-01-2011
2,       John,      1002, 2,      01-01-2011
2,       John,      1003, 3,      01-01-2011

content, trackno, tmstamp
001,      1,       01-01-2011
002,      1,       01-01-2011
001,      2,       01-01-2011
002,      2,       01-01-2011
003,      2,       01-01-2011
001,      3,       01-01-2011

结果

StaffName, tmstamp,   noOfQno, noOfContent
James,     01-01-2011, 1,       2
John,      01-01-2011, 2,       4

VisitMatter是2个表格。

结果是我想要的结果。

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT StaffName, tmstamp, noOfQno, noOfContent
  FROM (
                SELECT StaffName, tmstamp, trackno, COUNT(1) noOfQno
                    FROM Visit
                GROUP BY StaffName, tmstamp, trackno
             ) a LEFT JOIN
             (
                SELECT trackno, COUNT(1) noOfContent
                    FROM Matter 
                GROUP BY    trackno
             ) b
    ON  b.trackno = a.trackno

答案 1 :(得分:1)

SELECT
  v.StaffName,
  v.tmstamp,
  noOfQno = COUNT(DISTINCT v.qno),
  noOfContent = COUNT(m.content)
FROM Visit v
  LEFT JOIN Matter m ON v.trackno = m.tracno AND v.tmstamp = m.tmstamp
GROUP BY v.StaffName, v.tmstamp

答案 2 :(得分:0)

与Cyber​​nates的答案相同,但CTE:

;with MattersGrouped as (
    select trackno, COUNT(*) noOfContent
    from Matter
    group by trackno
),
VisitsGrouped as (
    select Staffname, trackno, tmstamp, COUNT(*) noOfQno
    from Visit
    group by Staffname, trackno, tmstamp
)
select t1.StaffName, t1.tmstamp, t2.noOfContent, t1.noOfQno
from VisitsGrouped t1 left join MattersGrouped t2 on (t1.trackno = t2.trackno)