开发者社区> 问答> 正文

SQL Server中的时间范围仅适用于日期

我有一个名为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

展开
收起
祖安文状元 2020-01-03 16:35:22 628 0
1 条回答
写回答
取消 提交回答
  • 在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
    )
    
    2020-01-03 16:35:34
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
SQL Server在电子商务中的应用与实践 立即下载
GeoMesa on Spark SQL 立即下载
原生SQL on Hadoop引擎- Apache HAWQ 2.x最新技术解密malili 立即下载