一次选择所有

时间:2009-09-23 12:59:18

标签: sql

我想从下表中选择patient_id和日期差异:

p_id    TreatmentDate
15      2008-05-01
15      2008-05-03
15      2008-05-05
15      2008-05-07
16      2008-05-01
16      2008-05-03
16      2008-05-05
16      2008-05-09
16      2008-05-11
17      2008-05-03
17      2008-05-05
17      2008-05-07

我希望得到这样的结果:

p_id      Day Difference
15        6 Days
16        10 Days
17        4 Days

您是否有任何可以在sql语句中生成此结果的商品?

4 个答案:

答案 0 :(得分:8)

这应该可以正常使用

select p_id, max(TreatmentDate) - min(TreatmentDate) from 
patientsTable group by p_id

更具体地说,对于MSSQL Server

select p_id, DATEDIFF(D, MIN(TreatmentDate), MAX(TreatmentDate)) from 
patientsTable group by p_id

答案 1 :(得分:3)

MS SQL Server:

SELECT 
    p_id, 
    STR(DATEDIFF(DAY, MIN(TreatmentDate), MAX(TreatmentDate))) + ' Days' AS DayDifference
FROM 
    table 
GROUP BY 
    p_id

答案 2 :(得分:2)

MS SQL:

select
    p_id,
    datediff(d, min(TreatmentDate), max(TreatmentDate)) AS DayDifference
from 
    patientsTable
group by
    p_id;

答案 3 :(得分:1)

这将有效:

SELECT p_id, CONCAT(max(TreatmentDate) - min(TreatmentDate),' Days') as "Day Difference" 
FROM
patient_info 
GROUP BY p_id;

鉴于此架构/数据:

CREATE TABLE patient_info (
p_id INT,
TreatmentDate DATE
);
INSERT INTO patient_info 
VALUES 
(15,'2008-05-01'),
(15,'2008-05-03'),
(15,'2008-05-05'),
(15,'2008-05-07'),
(16,'2008-05-01'),
(16,'2008-05-03'),
(16,'2008-05-05'),
(16,'2008-05-09'),
(17,'2008-05-03'),
(17,'2008-05-05'),
(17,'2008-05-07');

+------+----------------+
| p_id | Day Difference |
+------+----------------+
|   15 | 6 Days         | 
|   16 | 8 Days         | 
|   17 | 4 Days         | 
+------+----------------+
3 rows in set (0.00 sec)

如果您需要更多帮助,请与我们联系。