简体   繁体   English

格式化计算数据

[英]Format Calculated Data

I am trying to format of years and months in a manner like yy-mm我正在尝试以 yy-mm 之类的方式格式化年份和月份

I can calculate like this to get my year value:我可以这样计算以获得我的年份值:

ROUND(months_between(sysdate,hiringdate)/12)

And this to get the months value:这是为了获得月份值:

ROUND(months_between(sysdate,hiringdate))

I just dont know how to combine those 2 to get them in the yy-mm format我只是不知道如何将这两个组合起来以 yy-mm 格式

This looks like Oracle, so try this:这看起来像 Oracle,所以试试这个:

select (lpad(floor(months_between(sysdate, hiringdate)/12), 2, '0') || '-' ||
        lpad(mod(floor(months_between(sysdate, hiringdate)), 12), 2, '0')
       ) as yymm

It depends: there are many flavors of SQL.这取决于:SQL 有很多种。

In Oracle and standard SQL, you can use string1 || string2在 Oracle 和标准 SQL 中,您可以使用string1 || string2 string1 || string2 , string1 || string2 ,

In MySQL there's the CONCAT(string1, string2) function在 MySQL 中有CONCAT(string1, string2)函数

In SAS there's the COMPRESS(string1 || string2) statement, which looks like a combination of the above.在 SAS 中有COMPRESS(string1 || string2)语句,它看起来像上面的组合。

Search how to do it on your platform or let it know which one it is.搜索如何在您的平台上执行此操作或让它知道它是哪一个。

You could do something like this.你可以做这样的事情。 Using the EMP table in the SCOTT schema for testing.使用SCOTT模式中的EMP表进行测试。

select empno, ename, hiredate,
       to_char(floor(mths/12), 'fm99') || '-' || 
       to_char(mod(mths, 12) , 'fm00')  as yymm
from   ( 
         select empno, ename, hiredate, 
                round(months_between(sysdate, hiredate)) as mths
         from   scott.emp
       )
;
     EMPNO ENAME      HIREDATE    YYMM   
---------- ---------- ----------- -------
      7369 SMITH      17-DEC-1980 38-03  
      7499 ALLEN      20-FEB-1981 38-01  
      7521 WARD       22-FEB-1981 38-01  
      7566 JONES      02-APR-1981 38-00  
      7654 MARTIN     28-SEP-1981 37-06  
      7698 BLAKE      01-MAY-1981 37-11  
      7782 CLARK      09-JUN-1981 37-09  
      7788 SCOTT      19-APR-1987 31-11  
      7839 KING       17-NOV-1981 37-04  
      7844 TURNER     08-SEP-1981 37-06  
      7876 ADAMS      23-MAY-1987 31-10  
      7900 JAMES      03-DEC-1981 37-04  
      7902 FORD       03-DEC-1981 37-04  
      7934 MILLER     23-JAN-1982 37-02 

Probably a million ways to do this.可能有一百万种方法可以做到这一点。 One of them is this one:其中之一是这个:

SELECT RIGHT (CAST (YEAR (GETDATE()) AS VARCHAR(4)), 2) + '-' + RIGHT ('0' + CAST (MONTH (GETDATE()) AS VARCHAR (2)), 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM