SQL Server SQL -将符号的列值转换为名称为符号且类型为布尔值的列

nc1teljy  于 2022-11-21  发布在  其他
关注(0)|答案(4)|浏览(140)

我有一个包含“符号”列的表:

我需要将其转换为一个表,该表将符号的列值(不同的)作为新的列名。这些列的类型应为bool或INT(0/1)。生成的表应如下所示:

P.S.如果列集是由另一个查询动态生成的,该怎么办?

zzwlnbp8

zzwlnbp81#

如果需要动态列,则需要动态SQL

示例

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName(Symbol)+'=case when symbol='''+Symbol+''' then 1 else 0 end ' From Yourtable  Order by 1 For XML Path('')),1,1,'') 

Select @SQL = '
Select '+@SQL+'
      ,PartOfDay
      ,isProfitable
 From  YourTable
'
Exec(@SQL)

退货

9rbhqvlz

9rbhqvlz2#

只需使用case

select (case when symbol = 'ACRX' then 1 else 0 end) as acrx,
       (case when symbol = 'ANF' then 1 else 0 end) as anf,
       (case when symbol = 'NVDA' then 1 else 0 end) as nvda,
       (case when symbol = 'rsx' then 1 else 0 end) as rsx,
       partofday, isprofitable
from t;
sg3maiej

sg3maiej3#

您可以

select 
  IIF('ACRX', 1, 0) as acrx,
  IIF('ANF', 1, 0) as anf,
  IIF('NVDA', 1, 0) as nvda,
  IIF('RXS', 1, 0) as rsx,
  partofday, 
  isprofitable
from t;
eni9jsuy

eni9jsuy4#

您还可以将透视运算符应用于动态SQL。
例如:

create table test03
(
Symbol varchar(30),
PartOfDay int,
isProfitable int
)

insert into test03 values
('ACRX',3,0),
('ACRX',3,0),
('ANF',2,1),
('ANF',2,1),
('ANF',2,1),
('NVDA',3,1),
('RSX',3,0),
('RSX',3,0)

--Query

DECLARE @V_COLUMNS VARCHAR(MAX)
DECLARE @V_SQL VARCHAR(MAX)
SET @V_COLUMNS=STUFF((SELECT DISTINCT ','+QUOTENAME(Symbol) FROM test03 FOR XML PATH('')),1,1,'')
--print @V_COLUMNS

SET @V_SQL='
;WITH CTE AS
(
select 
ROW_NUMBER() over (order by Symbol) as RN,
Symbol,
1 AS V_VALUE,
PartOfDay,
isProfitable
from test03
)
SELECT '+@V_COLUMNS+',PartOfDay,isProfitable
FROM CTE 
PIVOT 
(
COUNT(V_VALUE) FOR Symbol IN ('+@V_COLUMNS+')
) PVT'

--PRINT @V_SQL
EXEC(@V_SQL)

--Output
/*
ACRX        ANF         NVDA        RSX         PartOfDay   isProfitable
----------- ----------- ----------- ----------- ----------- ------------
1           0           0           0           3           0
1           0           0           0           3           0
0           1           0           0           2           1
0           1           0           0           2           1
0           1           0           0           2           1
0           0           1           0           3           1
0           0           0           1           3           0
0           0           0           1           3           0
*/

相关问题