我有一个如下表所示的记录,例如,同一客户有很多记录,但他们的EffectiveDate和RunDate可能相同或不同。 EffectiveDate和RunDate也可能包括TimeStamp,如2014-02-09 14:15:30.000,并且时间戳可能在同一日期有所不同。
ID Client EffectiveDate RunDate
1 abc 01-01-2014 14:15:30.000 09-02-2014 14:15:30.000
2 abc 02-01-2014 14:15:30.000 10-01-2014 14:15:30.000
3 abc 02-01-2014 15:19:30.000 09-01-2014 15:19:30.000
4 abc 03-01-2014 14:15:30.000 10-01-2014 14:15:30.000
5 abc 03-01-2014 15:20:30.000 09-01-2014 15:20:30.000
6 abc 02-01-2014 14:15:30.000 10-01-2014 14:15:30.000
7 abc 04-01-2014 14:30:30.000 10-01-2014 14:30:30.000
8 abc 04-01-2014 17:15:30.000 10-01-2014 17:15:30.000
我需要一个sql查询,其结果与相同的EffectiveDate相同,它将计算该客户端的记录数,而不管EffectiveDate的Timestamp和RunDate(包括其Timestamp)。我需要像
这样的结果 ID Client EffectiveDate Number Of Records
1 abc 01-01-2014 1
2 abc 02-01-2014 3
4 abc 03-01-2014 2
7 abc 04-01-2014 2
我知道可以在sql查询中使用Group By但是如果在日期中有时间戳,那么我无法获得所需的结果。
答案 0 :(得分:1)
使用以下查询获取结果:
SELECT ID, Client, EffectiveDate, RunDate
FROM
(SELECT ROW_NUMBER() OVER (PARTITION BY A.Client, B.EffectiveDate,
B.NumberOfRecords ORDER BY A.ID) AS RowNum,
A.ID, A.Client, B.EffectiveDate, CONVERT(VARCHAR(10), A.RunDate ,105)
AS RunDate, B.NumberOfRecords
FROM #Temp A
INNER JOIN (SELECT Client, CONVERT(VARCHAR(10),EffectiveDate ,105) AS
EffectiveDate, COUNT(*) AS NumberOfRecords
FROM #Temp
GROUP BY Client, CONVERT(VARCHAR(10),EffectiveDate ,105)) B
ON A.Client = B.Client AND CONVERT(VARCHAR(10), A.EffectiveDate ,105) =
B.EffectiveDate) AS C
WHERE RowNum = 1
答案 1 :(得分:0)
您需要convert datetime to date
删除timestamp
group by
select Client,convert(date,EffectiveDate), count(1) [Number Of Records]
from tablename
group by Client,convert(date,EffectiveDate)
如果你想要Id的结果,那么试试这个(未经测试)。
;WITH cte
AS (SELECT Row_number() OVER(partition BY CONVERT(DATE, EffectiveDate) ORDER BY id) rn,*
FROM tablename)
SELECT a.ID,
a.Client,
a.EffectiveDate,
b.[Number Of Records]
FROM cte a
JOIN(SELECT Client,
CONVERT(DATE, EffectiveDate) EffectiveDate,
Count(1) [Number Of Records]
FROM tablename
GROUP BY Client,
CONVERT(DATE, EffectiveDate)) b
ON CONVERT(DATE, a.EffectiveDate) = b.EffectiveDate
where rn =1
答案 2 :(得分:0)
像这样选择日期部分
select convert(varchar,getdate(),105)
也用相同的
分组答案 3 :(得分:0)
select min(id) id,client,trunc(effectivedate) effectivedate,
min(trunc(rundate)) rundate,
count(client) no_of_records
from tempd
group by client,trunc(effectivedate)
order by 1
你可以尝试这个在oracle sql中运行良好和快速的工作,对于rundate,取决于你想要保持最小或最大的一个;在这个查询中我保持最小如果你想要最大然后把max而不是min,你会得到你想要的结果。
答案 4 :(得分:0)
尝试以下查询:
SELECT Min(ID) AS ID,
Client,
CONVERT(DATE,EffectiveDate) AS EffectiveDate,
MIN(RunDate) AS RunDate,
COUNT(*) AS [Number Of Records]
FROM ClientTableName
GROUP BY Client, CONVERT(Date,EffectiveDate)
注意:唯一的区别是返回的日期格式。这可以很容易地改为所需的格式