我在下面的订单中有一个包含ID和位的表:
ID Bit
1 0
1 0
1 1
1 0
1 0
1 0
1 1
1 0
1 1
1 0
1 ...
... ...
2 0
2 1
2 0
2 0
2 1
2 0
2 0
2 0
2 1
2 0
2 ...
... ...
n ...
如何对ID列进行分组并使用CTE将Bit列连接到varbinary列?
ID Bits
1 0x...
2 0x...
提前致谢...
答案 0 :(得分:0)
这应该有用......
declare @bits TABLE(ID INT, myBit BIT, Position INT);
insert into @bits values(1,0,0)
,(1,0,1)
,(1,1,2)
,(1,0,3)
,(1,0,4)
,(1,0,5)
,(1,1,6)
,(1,0,7)
,(1,1,8)
,(1,0,9)
,(2,0,0)
,(2,1,1)
,(2,0,2)
,(2,0,3)
,(2,1,4)
,(2,0,5)
,(2,0,6)
,(2,0,7)
,(2,1,8)
,(2,0,9);
WITH myIDs AS
(
SELECT DISTINCT ID
FROM @bits
)
SELECT '0x' + concatenatedBits.string
FROM myIDs
CROSS APPLY
(
SELECT
(
SELECT CAST(myBit AS VARCHAR(1))
FROM @bits AS b
WHERE b.ID=myIDs.ID
ORDER BY Position
FOR XML PATH(''),TYPE
).value('.','varchar(max)')
) AS concatenatedBits(string)