SQL查询数据透视表列入列

时间:2016-04-05 08:02:54

标签: sql-server sql-server-2008 pivot-table

我有这样的数据,我想在列中创建矩阵结果。

Seq JobNo       TrnDate     TrnHour
1   J-000198    2016-04-02  5
2   J-000198    2016-04-03  4
3   J-000198    2016-04-04  8
4   J-000198    2016-04-05  7
5   J-000198    2016-04-06  2
6   J-000198    2016-04-07  3
7   J-000198    2016-04-08  6

2016-04-02 TrnDate当天是星期六,依此类推。我希望通过sql查询得到这样的结果,并在gridview中填充以由用户添加/编辑。

Saturday Sunday Monday Tuesday Wednesday Thursday Friday
02       03     04     05      06        07       08
5        4      8      7       2         3        6

这可能吗?请帮忙。感谢

被修改---------

每个JobNo的完整月份条目。它是每天的总和。例如,如果我再添加一行这样的行,则为星期六日期9 + 2 = 11和小时5 + 5 = 10进行求和。我希望每周都能分开。

Seq JobNo       TrnDate     TrnHour
8   J-000198    2016-04-09  5

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT col, [Saturday], [Sunday], [Monday], [Tuesday], 
       [Wednesday], [Thursday], [Friday]
FROM (
  SELECT JobNo, x.col, x.val,
         DATENAME(WEEKDAY, TrnDate) AS d
  FROM mytable
  CROSS APPLY (
     VALUES ('Hour', TrnHour), 
            ('Day', DATEPART(dd, TrnDate))) x(col, val)  
) AS src
PIVOT (SUM(val) FOR d IN ([Saturday], [Sunday], [Monday], [Tuesday], 
                          [Wednesday], [Thursday], [Friday])) AS pvt

Demo here

要计算不同的周数,您必须在用于生成SELECT操作的源表的查询的PIVOT子句中包含周数:

SELECT col, w, [Saturday], [Sunday], [Monday], [Tuesday], [Wednesday], [Thursday], [Friday]
FROM (
  SELECT JobNo, x.col, x.val, 
         DATEPART(WEEK, TrnDate) AS w,
         DATENAME(WEEKDAY, TrnDate) AS d
  FROM mytable
  CROSS APPLY (
     VALUES ('Hour', TrnHour), ('Day', DATEPART(dd, TrnDate))) x(col, val)   
  ) AS t
PIVOT (SUM(val) FOR d IN ([Saturday], [Sunday], [Monday], [Tuesday], 
                              [Wednesday], [Thursday], [Friday])) AS pvt
ORDER BY w, col

Demo here

答案 1 :(得分:0)

你可以这样做。

SELECT info, [Saturday], [Sunday], [Monday], [Tuesday],[Wednesday],[Thursday], [Friday]
FROM (
    SELECT 'Total Hour' as info, JobNo, trnHour,DATENAME(WEEKDAY, TrnDate) AS d FROM JobTable   
    union all
    SELECT 'Date' info,JobNo, datepart(day,TrnDate) as trnHour,DATENAME(WEEKDAY,TrnDate) AS d FROM JobTable 
) AS src
PIVOT (SUM(trnHour) FOR d IN ([Saturday], [Sunday], [Monday], [Tuesday],[Wednesday], [Thursday], [Friday])) AS pvt

周明智。

SELECT [week],info, [Saturday], [Sunday], [Monday], [Tuesday],[Wednesday],[Thursday], [Friday]
FROM (
    SELECT 'Total Hour' as info, JobNo, trnHour,DATENAME(WEEKDAY, TrnDate) AS d,datepart(week,TrnDate) [week] FROM JobTable 
    union all
    SELECT 'Date' info,JobNo, datepart(day,TrnDate) as trnHour,DATENAME(WEEKDAY,TrnDate) AS d,datepart(week,TrnDate) [week] FROM JobTable   
) AS src
PIVOT (SUM(trnHour) FOR d IN ([Saturday], [Sunday], [Monday], [Tuesday],[Wednesday], [Thursday], [Friday])) AS pvt