8

此查询基于事务表编写

SELECT Ecode,COUNT(*) AS recvd 
FROM Transaction_tbl 
WHERE Locid=5 AND dtime BETWEEN '5/1/2013 00:00:00' AND '6/10/2013 23:59:59' 
GROUP BY Ecode 
ORDER BY Ecode DESC 

在执行此查询时,我会像这样

Ecode        recvd
E003           24
E001            2

我还有一张像员工主表这样的表,对应的员工姓名是保存,我如何将此表加入员工主表

我想像这样出去

Ecode Ename Recvd
E003   jas   24
E001   deepu  14
4

4 回答 4

10

尝试

SELECT e.Ecode, e.Ename, q.recvd
  FROM Employee e JOIN
(
    SELECT Ecode,COUNT(*) Recvd 
      FROM Transaction_tbl 
     WHERE Locid = 5 
       AND dtime BETWEEN '5/1/2013 00:00:00' AND '6/10/2013 23:59:59' 
     GROUP BY Ecode 
) q ON e.Ecode = q.Ecode
 ORDER BY e.Ecode DESC

要不就

SELECT e.Ecode, e.Ename, COUNT(*) Recvd 
  FROM Employee e JOIN Transaction_tbl t
    ON e.Ecode = t.Ecode
 WHERE Locid = 5 
   AND dtime BETWEEN '5/1/2013 00:00:00' AND '6/10/2013 23:59:59' 
 GROUP BY e.Ecode DESC

这是SQLFiddle演示。

于 2013-06-16T14:15:31.920 回答
2

我认为您可以使用INNER JOIN查询

SELECT a.Ecode,COUNT(a.*) AS recvd, b.name
FROM Transaction_tbl a
INNER JOIN employee_master b
ON a.id = b.id
WHERE a.Locid=5 
AND a.dtime BETWEEN '5/1/2013 00:00:00' AND '6/10/2013 23:59:59' 
GROUP BY a.Ecode 
ORDER BY a.Ecode DESC 

只需更改ON a.id = b.id具有关系和表名的实际列名即可。

于 2013-06-16T14:17:42.113 回答
1

您的 EmployeeMaster 表或 Transaction_tbl 中必须有一个外键才能执行您想要的操作,如果您这样做,这只会有所帮助

如果外键在 EmployeeMaster

    SELECT t.Ecode,e.Ename,t.COUNT(*) AS recvd
    FROM Transaction_tbl as t
    INNER JOIN EmployeeMaster as e
    ON t.Ecode = e.Ecode
    WHERE t.Locid=5 AND dtime BETWEEN '5/1/2013 00:00:00' AND '6/10/2013 23:59:59' 
    GROUP BY t.Ecode 
    ORDER BY t.Ecode DESC 

如果它在 Transaction_tbl

    SELECT t.Ecode,e.Ename,t.COUNT(*) AS recvd
    FROM Transaction_tbl as t
    INNER JOIN EmployeeMaster as e
    ON t.EmasterForeignKey = e.EmasterPrimaryKey
    WHERE t.Locid=5 AND dtime BETWEEN '5/1/2013 00:00:00' AND '6/10/2013 23:59:59' 
    GROUP BY t.Ecode 
    ORDER BY t.Ecode DESC 

我希望它有帮助

于 2013-06-16T14:22:14.193 回答
1
SELECT t.Ecode, e.name, COUNT(*) AS recvd 
FROM Transaction_tbl 
JOIN Employee e ON e.Ecode = t.Ecode
WHERE Locid=5
AND dtime BETWEEN '5/1/2013 00:00:00' AND '6/10/2013 23:59:59' 
GROUP BY t.Ecode, e.name
ORDER BY Ecode DESC
于 2013-06-16T14:17:17.847 回答