TSQL UNPIVOT 数月 +迄今为止的年份栏

发布于 2025-01-04 12:52:44 字数 552 浏览 2 评论 0原文

我在 SQL Server 2008 中有这个表结构:

列:PersonID,DOSE1,DOSE2,DOSE3,..... DOSE12,YEAR

示例行:123, 0.1, 0.0, 0.5,..... 0.7, 2008

所以基本上我每个月有一列,然后是年份。

这些行包含当年每个月份的剂量值。

我想要的输出是:

列:PersonId、BeginDate、EndDate、Dose

BeginDate 和 EndDate 将从 DOSEx 列和年份派生。 所以说年份是 2008 年,DOSE1 列会给我一个 BeginDate 01/01/2008 结束 EndDate 应该是 31/01/2008 23:59

对于 DOSE4 来说是四月,所以 BeginDate 应该是 01/04/ 2008 和 EndDate 30/04/2008 23:59

使用 TSQL 实现此目的的任何方法?我怀疑我应该使用 UNPIVOT,但不太确定如何到达那里。

非常感谢任何帮助。

问候,

TJ

I have this table structure in SQL Server 2008:

Columns: PersonID, DOSE1, DOSE2, DOSE3, ..... DOSE12, YEAR

example row: 123, 0.1, 0.0, 0.5, ..... 0.7, 2008

So basically I have a column for each month, and then a column year.

And the rows contain dose values for each of these months of that year.

My desired output is:

Columns: PersonId, BeginDate, EndDate, Dose

BeginDate and EndDate would be derived from the DOSEx columns, and the year.
So say the year is 2008, the DOSE1 column would give me a BeginDate of 01/01/2008 end the EndDate should be 31/01/2008 23:59

For DOSE4 it's the month of April, so BeginDate should be 01/04/2008 and EndDate 30/04/2008 23:59

Any way to achieve this using TSQL ? I have a suspicion I should be using UNPIVOT, but not really sure how to get there.

Any help is much appreciated.

Regards,

TJ

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

べ繥欢鉨o。 2025-01-11 12:52:44

这应该有效:

;WITH CTE AS
(
    SELECT  PersonId, 
            CONVERT(DATETIME,CAST([YEAR] AS VARCHAR(4))+RIGHT('0'+SUBSTRING(Months,5,2),2)+'01') BeginDate,
            Dose
    FROM YourTable A
    UNPIVOT(Dose FOR Months IN (DOSE1,DOSE2,DOSE3,DOSE4,DOSE5,DOSE6,DOSE7,DOSE8,DOSE9,DOSE10,DOSE11,DOSE12)) UP
)

SELECT PersonId, BeginDate, DATEADD(MINUTE,-1,DATEADD(MONTH,1,BeginDate)) EndDate, Dose
FROM CTE

This should work:

;WITH CTE AS
(
    SELECT  PersonId, 
            CONVERT(DATETIME,CAST([YEAR] AS VARCHAR(4))+RIGHT('0'+SUBSTRING(Months,5,2),2)+'01') BeginDate,
            Dose
    FROM YourTable A
    UNPIVOT(Dose FOR Months IN (DOSE1,DOSE2,DOSE3,DOSE4,DOSE5,DOSE6,DOSE7,DOSE8,DOSE9,DOSE10,DOSE11,DOSE12)) UP
)

SELECT PersonId, BeginDate, DATEADD(MINUTE,-1,DATEADD(MONTH,1,BeginDate)) EndDate, Dose
FROM CTE
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文