这可能是一个非常简单的问题。我想要做的就是将列放入一个数据类型有点的行。
SUM,MIN,MAX对位不起作用。 COUNT有效,但我真的不想数。我只想将所有的东西从列移到行中,就像我拿了一把剪刀,切割信息并移动-90度。
答案 0 :(得分:5)
解决方案是将位数据类型转换为聚合函数中接受的数据类型。例如,
SELECT MAX(CAST(BitColumn AS TINYINT))
将BitColumn值转换为tinyint数据类型。如果BitColumn包含至少一个值1,则该语句返回1;否则,它返回0(除非所有值都为空)。
假设如下:
CREATE TABLE MyTable (ID INT, Name VARCHAR(10), BitColumn BIT);
INSERT INTO MyTable VALUES (1, 'Name 1', 1);
INSERT INTO MyTable VALUES (1, 'Name 2', 0);
INSERT INTO MyTable VALUES (1, 'Name 3', 1);
INSERT INTO MyTable VALUES (2, 'Name 1', 1);
INSERT INTO MyTable VALUES (2, 'Name 2', 1);
INSERT INTO MyTable VALUES (2, 'Name 3', 1);
INSERT INTO MyTable VALUES (3, 'Name 1', 0);
INSERT INTO MyTable VALUES (3, 'Name 2', 0);
INSERT INTO MyTable VALUES (3, 'Name 3', 0);
您可以使用以下查询
来转移此数据SELECT ID,
CAST(MAX(CASE Name WHEN 'Name 1' THEN CAST(BitColumn AS TINYINT) ELSE NULL END) AS BIT) AS [Name 1],
CAST(MAX(CASE Name WHEN 'Name 2' THEN CAST(BitColumn AS TINYINT) ELSE NULL END) AS BIT) AS [Name 2],
CAST(MAX(CASE Name WHEN 'Name 3' THEN CAST(BitColumn AS TINYINT) ELSE NULL END) AS BIT) AS [Name 3]
FROM MyTable
GROUP BY ID
ORDER BY ID
在这种情况下,最大BitColumn值从tinyint转换回bitint。这不是必需的。
结果
ID Name 1 Name 2 Name 3
--------------------------
1 1 0 1
2 1 1 1
3 0 0 0
SQL Server 2005及更高版本的替代查询使用PIVOT运算符
SELECT ID, [Name 1], [Name 2], [Name 3]
FROM
(
SELECT ID, Name, CAST(BitColumn AS TINYINT) AS BitColumn
FROM MyTable
) as SourceTable
PIVOT
(
MAX(BitColumn) FOR Name in ([Name 1], [Name 2], [Name 3])
) AS PivotTable
答案 1 :(得分:2)
SELECT [1], [2], [3]
FROM
(
SELECT ID, CAST(BitColumn AS TINYINT) AS INTColumn
FROM MyTable
) as SourceTable
PIVOT
(
MAX(INTColumn) FOR ID in ([1], [2], [3])
) AS PivotTable