在 SQL Server 中使用 Pivot 将日期显示为星期几

Using Pivot in SQL Server to Display dates as days of the week(在 SQL Server 中使用 Pivot 将日期显示为星期几)
本文介绍了在 SQL Server 中使用 Pivot 将日期显示为星期几的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,其中有一列类型为 DateTime, 我想以 datetime 列为中心,以便日期显示为列(如星期一、星期二等).

I have table that has a column of type DateTime, I would like to pivot on the datetime column so that the dates are displayed as columns (as days of the week Monday, Tuesday etc).

例如,我有一个这样的表(不记得 SQL Server 是如何显示完整日期时间的,但你明白了):

So for example I have a table like this (can't remember how SQL Server displays full datetimes but you get the idea):

BugNo | DateOpened | TimeSpent

1234  | 16/08/2010 | 1.0 
4321  | 16/08/2010 | 3.5 
9876  | 17/08/2010 | 1.5 
6789  | 18/08/2010 | 7.0 
6789  | 19/08/2010 | 6.5 
6789  | 20/08/2010 | 2.5

我想以 DateOpened 列为中心来创建这样的结果集

I would like to pivot on the DateOpened column to create a result set like this

|TimeSpentOnBugByDay|  Mon  |  Tue  | Wed | Thu  | Fri | Sat | Sun
1234                    1
4321                    3.5
9876                           1.5
6789                                   7.0
6789                                         6.5
6789                                                2.5

我应该指出,我一次只能检索一个星期.

I should point out that I'll only be retrieving one week at a time.

我不确定这是否可能,但我很确定我以前见过类似的东西(不是我写的).

I'm not sure if this is possible, though I'm pretty certain I have seen something like this before (that I didn't write).

推荐答案

你可以这样做

SELECT BugNo, [Monday], [Tuesday], [Wednesday], [Thursday], [Friday], [Saturday], [Sunday]
FROM (
    SELECT BugNo, DATENAME(dw, DateOpened) AS DayWeek, TimeSpent
    FROM Bugs
    ) AS src
    pivot (
        SUM(TimeSpent) FOR DayWeek IN ([Monday], [Tuesday], [Wednesday], [Thursday], [Friday], [Saturday], [Sunday])
    ) AS pvt

这篇关于在 SQL Server 中使用 Pivot 将日期显示为星期几的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)