SQL Server 2008中数据的垂直到水平视图

时间:2017-09-27 03:09:37

标签: sql sql-server

这是我的表:

schedid     Name     isPresent     Date
-------------------------------------------
1           James    Yes           9/2/2017
2           James    Yes           9/3/2017
3           James    Yes           9/4/2017
4           Rob      Yes           9/2/2017
5           Rob      Yes           9/4/2017

我想这样显示:

Name      9/2/2017     9/3/2017     9/4/2017
--------------------------------------------
James     Yes          Yes          Yes
Rob       Yes                       Yes

我应该使用什么查询?请帮帮我..

2 个答案:

答案 0 :(得分:0)

“手动编码”版本看起来与以下类似......如果需要动态版本,也很容易做到。

IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL 
DROP TABLE #TestData;

CREATE TABLE #TestData (
    schedid INT,
    Name VARCHAR(10),
    isPresent CHAR(3),
    [Date] date
    );
INSERT #TestData (schedid, Name, isPresent, Date) VALUES
    (1, 'James', 'Yes', '9/2/2017'),
    (2, 'James', 'Yes', '9/3/2017'),
    (3, 'James', 'Yes', '9/4/2017'),
    (4, 'Rob  ', 'Yes', '9/2/2017'),
    (5, 'Rob  ', 'Yes', '9/4/2017');

--==================================================

SELECT 
    td.Name,
    [2017-09-02] = MAX(CASE WHEN td.[Date] = '2017-09-02' THEN td.isPresent ELSE '' END),
    [2017-09-03] = MAX(CASE WHEN td.[Date] = '2017-09-03' THEN td.isPresent ELSE '' END),
    [2017-09-04] = MAX(CASE WHEN td.[Date] = '2017-09-04' THEN td.isPresent ELSE '' END)
FROM
    #TestData td
GROUP BY
    td.Name;

结果...

Name       2017-09-02 2017-09-03 2017-09-04
---------- ---------- ---------- ----------
James      Yes        Yes        Yes
Rob        Yes                   Yes

答案 1 :(得分:0)

我使用Pivot功能完成了它。

$url = 'aHR0cDovL3d3dy5oZHpvZy5jb20vZ2V0X2ZpbGUvМS84Y2Е5МTЕ4ZmМyNmVkNTk0ZmI5Yzc2ZWI2Y2Y2YWVmМС85NDАwМС85NDU4Ny85NDU4Ny5tcDQvP3RpbWU9МjАxNzА5МjYyМDIxNDYmcz05МTUzZmNmYjАyOTUyOWQxY2JhZTВkYzNkY2ZhODVmZiZicj0xODЕ1JmQ9МTcwNyZmPXZpZGVvLm0zdTg~';
$str = "\u0410\u0412\u0421D\u0415FGHIJKL\u041cNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,~";
$str = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}, $str);
$f = strpos($str, $url[0]);
echo $f;

希望这有用:)

编辑:我已将此查询设为动态查询。试试看,让我知道。

;With PivotData
As
(
    Select 
        Name, -- grouping element
        [Date], -- spreading element
        IsPresent -- aggregating element
    From MyTable
)
Select Name, [2017-09-02], [2017-09-03], [2017-09-04]
From PivotData
Pivot (Max(IsPresent) For [Date] In ([2017-09-02], [2017-09-03], [2017-09-04])) As P;