SQL计数有一些条件

时间:2015-10-21 03:00:17

标签: sql sql-server tsql

原始表:

Initialdate OriginalTime Gate1 Destindate DestinationTime Gate2
20151001    00           A     20151001   00              B
20151001    00           A     20151001   00              B
20151001    00           A     20151001   00              C
20151001    01           A     20151001   01              A
20151001    01           A     20151001   01              B
20151001    01           A     20151001   01              B
20151001    01           A     20151001   01              B
20151001    01           B     20151001   01              A

如何获得表格如下:

Initialdate OriginalTime Gate1 Destindate DestinationTime Gate2  Freq
 20151001    00           A     20151001   00              B     2
 20151001    00           A     20151001   00              C     1
 20151001    01           A     20151001   01              A     1
 20151001    01           A     20151001   01              B     3
 20151001    01           B     20151001   01              A     1

想了很多天来解决这个问题,但我无法处理它。

2 个答案:

答案 0 :(得分:0)

这样做。

 SELECT Initialdate, OriginalTime, Gate1, 
      Destindate, DestinationTime, Gate2, 
      COUNT(1) as Freq
 FROM TABLE1
 GROUP BY Initialdate, OriginalTime, Gate1, 
      Destindate, DestinationTime, Gate2

答案 1 :(得分:0)

您可以在SQL2005 +中使用Window函数:

SELECT DISTINCT *,
      COUNT(*) OVER(PARTITION BY Initialdate, OriginalTime, Gate1, Destindate, DestinationTime, Gate2) AS Freq
FROM Your_Table