如何在MSSQL中的子查询中使用count

时间:2017-06-28 10:37:14

标签: sql-server

我想在mssql中合并两个表。第一个表有一个任务列。我想计算具体任务,并将计数结果提供给AuftNr的第二个表。

此处enter image description here

我是否需要子查询和分组才能解决此问题?

到目前为止,我已经做到了这一点。

    SELECT AB.PersNr as PersonalNumber

      ,CONVERT(char(10),DATEADD(DAY, AB.Tag, '30.12.1899'),126) AS Day
      ,CONVERT(char(10),DATEADD(SECOND, AB.Von, DATEADD(DAY, AB.Tag, 
   '30.12.1899')),108) AS [From]
      ,AB.Bis as [To]
      ,AB.Auftrag as Task
   FROM AStpVonBis AB
    LEFT JOIN Auftrag A ON (A.AuftNr = AB.Auftrag)
    INNER JOIN Personen P ON (P.PersNr = AB.PersNr)
   WHERE P.Abteilung = 170 AND AB.Tag = DATEDIFF(DAY, '30.12.1899', GETDATE()) 
   AND AB.Bis = -2 


   SELECT  A.AuftNr FROM Auftrag A 

2 个答案:

答案 0 :(得分:1)

使用GROUP BY和COUNT应该这样做:

SELECT 
 AB.Auftrag as Task,
 count(*) as Total
FROM AStpVonBis AB
JOIN Personen P ON (P.PersNr = AB.PersNr)
WHERE P.Abteilung = 170 
AND AB.Tag = DATEDIFF(DAY, convert(date,'30.12.1899',104), GETDATE())
AND AB.Bis = -2
GROUP BY AB.Auftrag
ORDER BY AB.Auftrag

请注意,未包括与[Auftrag]的左连接 由于已经有AB.Auftrag分组,并且在任务名称上不需要分组。

日期戳是converted with the 104 format到日期 这样它也适用于使用其他默认日期格式的连接。

免责声明:仅在记事本中测试

答案 1 :(得分:0)

如果我理解你的问题,那么下面的查询应该可以正常工作

DECLARE @Count TABLE (PhoneNumver INT, [Day] DATE,[From] VARCHAR(150),[To] VARCHAR(3),Task INT)
INSERT INTO @Count  
VALUES(1003,'2017-06-28','07:46:20','-2',150 ),
      (1010,'2017-06-28','11:44:47','-2',140),
      (1012,'2017-06-28','10:57:00','-2',120 ),
      (1016,'2017-06-28','12:20:16','-2',120 ), 
      (1019,'2017-06-28','08:31:03','-2',120 ),
      (1020,'2017-06-28','11:38:02','-2',120 ),
      (1021,'2017-06-28','07:54:55','-2',120 ),
      (1025,'2017-06-28','11:38:12','-2',120 ),
      (1027,'2017-06-28','09:47:46','-2',130 )

DECLARE @Task TABLE (AuftNr INT)
INSERT INTO @Task VALUES (110),(120),(130),(140),(150),(200),(210),(220),(230)


SELECT
A.AuftNr,
COUNT(C.Task) AS Total_Count
FROM @Task A
LEFT JOIN @Count C ON A.AuftNr=C.Task

--From here you can add all the exclussions in where clause 
GROUP BY A.AuftNr
ORDER BY Total_Count DESC

输出

AuftNr  Total_Count
120         6
130         1
140         1
150         1
200         0
210         0
220         0
230         0
110         0