how to link the following 2 tables to get the result which is shown below in SQL Server?`

送分小仙女□ 提交于 2019-12-12 04:59:36

问题


Visit

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

Matter

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

Result

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

Visit and Matter are 2 tables.

The result is the result I want.

How can I achieve that?


回答1:


Try this:

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



回答2:


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



回答3:


Same as Cybernates answer, but with 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)


来源:https://stackoverflow.com/questions/4835208/how-to-link-the-following-2-tables-to-get-the-result-which-is-shown-below-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!