简体   繁体   English

你如何在SQL Server中的Bit数据类型上进行PIVOT?

[英]How do you PIVOT on a Bit datatype in SQL Server?

This is probably a very simple question. 这可能是一个非常简单的问题。 All I want to really do is to make the column into a row whose data type is a bit. 我想要做的就是将列放入一个数据类型有点的行。

SUM, MIN, MAX doesn't work on bits. SUM,MIN,MAX不适用于位。 COUNT works but I really don't want to count. COUNT有效,但我真的不想数。 I just want to move all the stuff from columns into rows like if I took a pair of scissors, cut the information and moved it -90 degrees. 我只想将所有的东西从列移到行中,就像我拿了一把剪刀,切割信息并移动-90度。

The solution to this is to cast the bit data type to a data type that is accepted in aggregate functions. 解决方案是将位数据类型转换为聚合函数中接受的数据类型。 For example, 例如,

SELECT MAX(CAST(BitColumn AS TINYINT))

casts the BitColumn value to a tinyint datatype. 将BitColumn值转换为tinyint数据类型。 The statement returns 1 if BitColumn contains at least one value of 1; 如果BitColumn包含至少一个值1,则该语句返回1; otherwise, it returns 0 (unless all values are null). 否则,它返回0(除非所有值都为null)。

Assuming the following: 假设如下:

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);

You can pivot this data using the following query 您可以使用以下查询来转动此数据

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

In this case, the max BitColumn value is converted back from tinyint to bit. 在这种情况下,最大BitColumn值从tinyint转换回bitint。 This is not required. 这不是必需的。

The results are 结果是

ID  Name 1  Name 2  Name 3
--------------------------
1   1       0       1
2   1       1       1
3   0       0       0

An alternative query, for SQL Server 2005 and later, uses the PIVOT operator 对于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
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM