我正在使用SQL Server 2010。
我在数据库中有一个表,其中包含如下所示的记录:
Id | EmpName | JoinDate | ResignedDate
---+----------+-------------------------+--------------
1 | Govind | 2014-04-02 00:00:00.000 | 2014-04-02
2 | Aravind | 2014-04-05 00:00:00.000 | 2014-04-05
3 | Aravind | 2014-04-07 00:00:00.000 | 2014-04-10
4 | Aravind | 2014-04-10 00:00:00.000 | 2014-04-11
5 | Aravind | 2014-04-14 00:00:00.000 | 2014-04-16
现在,我希望显示两个日期(joinDate,ResignDate)和该日期之间的差异,可用的数量不同
示例输出:
DateDifferent Count
------------- -----
0 2
1 1
2 1
3 1
这里显示的是我的示例查询
entityManager.createNativeQuery(SELECT
DATEDIFF(day, e.joinedDate , e.resignedDate),
COUNT(DATEDIFF(day, e.joinedDate , e.resignedDate)))
FROM
Employee e
GROUP BY
DATEDIFF(e.joinedDate , e.resignedDate) ORDER BY (DATEDIFF(e.joinedDate , e.resignedDate)));
此查询适用于mssql查询浏览器,但是当我在JPA Native Query(Java代码)中使用查询时,此查询无法正常工作
任何人帮助我......
答案 0 :(得分:0)
MS SQL Server 2008架构设置:
CREATE TABLE Employee
([Id] int, [EmpName] varchar(7), [JoinDate] datetime, [ResignedDate] datetime)
;
INSERT INTO Employee
([Id], [EmpName], [JoinDate], [ResignedDate])
VALUES
(1, 'Govind', '2014-04-02 00:00:00', '2014-04-02 00:00:00'),
(2, 'Aravind', '2014-04-05 00:00:00', '2014-04-05 00:00:00'),
(3, 'Aravind', '2014-04-07 00:00:00', '2014-04-10 00:00:00'),
(4, 'Aravind', '2014-04-10 00:00:00', '2014-04-11 00:00:00'),
(5, 'Aravind', '2014-04-14 00:00:00', '2014-04-16 00:00:00')
;
查询1 :
SELECT
DATEDIFF(DAY, JoinDate, ResignedDate) AS DateDifferent
, COUNT(DATEDIFF(DAY, JoinDate, ResignedDate)) as FrequencyOf
FROM Employee
GROUP BY DATEDIFF(DAY, JoinDate, ResignedDate)
ORDER BY DateDifferent
请注意!您可以在ORDER BY子句中使用列别名(例如DateDifferent)
<强> Results 强>:
| DateDifferent | FrequencyOf |
|---------------|-------------|
| 0 | 2 |
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |