难倒集团

时间:2014-12-12 20:06:43

标签: sql sql-server

我正在尝试获取特定日期的字段WOID的计数,问题是日期字段[opendate]是日期时间字段,所以我决定使用强制转换将[opendate]更改为日期字段

SELECT distinct
   cast([OPENDATE] as date) as [Opened Date]
  ,count([WOID]) as ID
FROM [Tasks]
Group by [OPENDATE]

问题是我得到这样的输出

Opened date ID 
2014-05-01  1
2014-05-01  1
2014-05-21  1 
2014-05-20  1

我期望得到像这样的正确计数

Opened date ID 
2014-05-01  4
2014-05-02  5

任何想法

4 个答案:

答案 0 :(得分:2)

您按照与所选内容不同的内容进行分组,请更改为:

SELECT cast([OPENDATE] as date) as [Opened Date]
      ,count([WOID]) as ID
FROM [Tasks]
Group by cast([OPENDATE] as date)

您可能在每个日期之后计算了不同的WOID,在这种情况下您将使用:

SELECT cast([OPENDATE] as date) as [Opened Date]
      ,count(DISTINCT [WOID]) as ID
FROM [Tasks]
Group by cast([OPENDATE] as date)

作为一般规则,SELECT中的所有非汇总项都应包含在GROUP BY中。 DISTINCT变得多余,可以排除。

答案 1 :(得分:0)

提供:

SELECT distinct
   cast([OPENDATE] as date) as [Opened Date]
  ,count([WOID]) as ID
FROM [Tasks]
Group by cast([OPENDATE] as date)

一个镜头 - 您希望将其分组到date,而不是datetime - 模仿您选择的列

答案 2 :(得分:0)

我假设你想要一个不同的WOID计数。如果是这样的话:

SELECT 
   cast([OPENDATE] as date) as [Opened Date]
  ,count(distinct [WOID]) as ID
FROM [Tasks]
Group by cast([OPENDATE] as date)

答案 3 :(得分:0)

更复杂的解决方案如下:

首先,您将收到所需格式的集:

SELECT cast([OPENDATE] as date) as [Opened Date] ,[WOID] as ID
FROM [Tasks]

然后,使用上述内容,您可以根据需要执行分组和计数,例如:

SELECT [Opened Date], ID = count([WOID])
FROM
(
    SELECT cast([OPENDATE] as date) as [Opened Date], [WOID]
    FROM [Tasks]
) x
Group by [Opened Date]

如果要计算每个数据的WOID的唯一值,可以按如下方式修改查询:

SELECT [Opened Date], ID = count(distinct [WOID])
FROM
(
    SELECT cast([OPENDATE] as date) as [Opened Date], [WOID]
    FROM [Tasks]
) x
Group by [Opened Date]

如果要使用窗口函数,查询可能如下所示:

SELECT distinct
   cast([OPENDATE] as date) as [Opened Date] ,
   count([WOID]) over (partition by cast([OPENDATE] as date) order by [WOID]) as ID
FROM [Tasks]