我有一个列接受NoOfMonths中我想用多年计算的值。我的表格结构如下所示
CREATE TABLE Duration
(
TotalMonths int
);
INSERT INTO Duration VALUES (24);
INSERT INTO Duration VALUES (18);
INSERT INTO Duration VALUES (7);
我希望结果显示如下,
Months Duration
24 2 Years
18 1 Year 6 Months
7 7 Months
答案 0 :(得分:3)
您可以获得此类数据
select duration,
duration / 12 as years,
duration % 12 as months
from your_table
您应该在程序的表示层中完成剩下的工作。
答案 1 :(得分:2)
试试这个
SELECT
*,
CASE WHEN TotalMonths>12
THEN CAST(TotalMonths/12 AS VARCHAR(10))+' Years '
ELSE '' END
+
CASE WHEN TotalMonths%12>0
THEN CAST(TotalMonths%12 AS VARCHAR(10))+' Months'
ELSE '' END
FROM Duration
答案 2 :(得分:2)
像这样的东西
DECLARE @Duration TABLE(TotalMonths int);
INSERT INTO @Duration VALUES (24),(18),(7);
SELECT d.TotalMonths
,A.*
, CASE WHEN A.CountYears>0 THEN CAST (A.CountYears AS VARCHAR(10)) + ' years ' ELSE '' END
+ CASE WHEN A.CountMonths>0 THEN CAST(A.CountMonths AS VARCHAR(10)) + ' months' ELSE '' END AS TextDescription
FROM @Duration AS d
CROSS APPLY(SELECT d.TotalMonths / 12 AS CountYears
,d.TotalMonths % 12 AS CountMonths) AS A;
编辑使用modulo operator %
结果
+-------------+------------+-------------+------------------+
| TotalMonths | CountYears | CountMonths | TextDescription |
+-------------+------------+-------------+------------------+
| 24 | 2 | 0 | 2 years |
+-------------+------------+-------------+------------------+
| 18 | 1 | 6 | 1 years 6 months |
+-------------+------------+-------------+------------------+
| 7 | 0 | 7 | 7 months |
+-------------+------------+-------------+------------------+
提示:整数除法将静默舍入为整数值。
答案 3 :(得分:1)
你可以这样做:
declare @Duration table (TotalMonths int)
INSERT INTO @Duration VALUES (24), (18), (7)
select d.TotalMonths as months,
case when d.TotalMonths / 12 > 0 then convert(varchar, d.TotalMonths / 12) + ' years ' else '' end
+
case when d.TotalMonths % 12 > 0 then convert(varchar, d.TotalMonths % 12) + ' Months' else '' end
as Duration
from @Duration d
结果是
months Duration
------ --------
24 2 years
18 1 years 6 Months
7 7 Months
答案 4 :(得分:0)
您需要检查如何显示虚拟列,并在其中进行数学运算。 像这样的东西
select TotalMonths, ((select TotalMonths from Duration) / 12) As DurationInYears from Duration
答案 5 :(得分:0)
这是一种简单的方法,您可以将整数值转换为月和日:
SELECT Duration(dd,366,0)
这会将持续时间值转换为数月和数年。