访问
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
Visit
和Matter
是2个表格。
结果是我想要的结果。
我怎样才能做到这一点?
答案 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)
与Cybernates的答案相同,但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)