我有一个名为Name的表Transactions,它包含这样的数据:
transaction_id cust_id tran_date
80712190438 270351 28-02-14
29258453508 270384 27-02-14
58387181112 275068 31-12-13
21300411973 274568 31-12-13
26229626485 267624 31-12-12
26229126485 267634 31-12-12
47557596721 273764 31-12-11
28966519600 273899 31-12-11
现在,可用于分析的交易数据的时间范围是多少?
问题的第二部分是:
显示在输出number of Days,Months并Years同时进行。
两者都应在“单个查询”中完成。
我使用下面的查询来获取天,月和年,但是我一直在寻找时间范围。
SELECT
MIN(CAST(CAST(tran_date AS NCHAR(8)) AS date)) AS Start_tran_Date
,MAX(CAST(CAST(tran_date AS NCHAR(8)) AS date)) AS End_tran_Date
,DATEDIFF(DAY,MAX(CAST(CAST(tran_date AS NCHAR(8)) AS date)), MIN(CAST(CAST(tran_date AS NCHAR(8)) AS date)) ) AS Difference_Days
,DATEDIFF(MONTH,MAX(CAST(CAST(tran_date AS NCHAR(8)) AS date)), MIN(CAST(CAST(tran_date AS NCHAR(8)) AS date)) ) AS Difference_Months
,DATEDIFF(YEAR,MAX(CAST(CAST(tran_date AS NCHAR(8)) AS date)), MIN(CAST(CAST(tran_date AS NCHAR(8)) AS date)) ) AS Difference_Years
FROM Transactions
但这给了我这个错误:
消息241,级别16,状态1,第50行从字符串转换日期和/或时间时转换失败。
我想要输出
tran_date_start tran_date_end No.of Days No.of Months No.of Years
在Anoymous的答案上,您可以使用子查询使代码更清晰-像这样:
SELECT
MIN(trans_dt) AS Start_tran_Date,
MAX(trans_dt) AS End_tran_Date,
DATEDIFF(DAY, MAX(trans_dt), MIN(trans_dt) ) AS Difference_Days,
DATEDIFF(MONTH,MAX(trans_dt), MIN(trans_dt) ) AS Difference_Months,
DATEDIFF(YEAR, MAX(trans_dt), MIN(trans_dt) ) AS Difference_Years
FROM (
SELECT transaction_id, cust_id, CONVERT(date,tran_date,3) as tran_dt
FROM Transaction
)
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。