切换列值

时间:2019-03-16 23:50:40

标签: sql sql-server tsql

我有2张这样的桌子。

MasterEntries中的列:

  ParishName    AverageMark    
  Hanover         50.00
  Manchester      65.00
  Andrew          70.00

MasterScoreSheet中的列:

 Hanover      Manchester    [St.Andrew]
 50.00        65.00         70.00

我希望将AverageMark中的MasterEntries列值变成相应列的值,如下所示:

 Hanover      Manchester    Andrew
 50.00        65.00         70.00

我该怎么做?

3 个答案:

答案 0 :(得分:1)

如果值固定为"Hanover","Manchester","Andrew",并且只有3行,则可以使用PIVOT()方法:

SELECT * 
FROM MasterEntries
     PIVOT(MAX(AverageMark) FOR ParishName IN ("Hanover","Manchester","Andrew")) AS AvgMark

答案 1 :(得分:1)

是否要将这些值插入表MasterScoreSheet中?
您可以这样做:

insert into MasterScoreSheet (Hannover, Manchester, Andrew)
select
  (select AverageMark from MasterEntries where ParishName = 'Hannover'),
  (select AverageMark from MasterEntries where ParishName = 'Manchester'),
  (select AverageMark from MasterEntries where ParishName = 'Andrew');

请参见demo

答案 2 :(得分:0)

我将使用条件聚合编写此查询:

url="www.google.com"

if expr.match(url):
    print("It is valid")