Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server PIVOT和IF语句还是条件语句?_Sql Server_Sql Server 2008_Tsql - Fatal编程技术网

Sql server PIVOT和IF语句还是条件语句?

Sql server PIVOT和IF语句还是条件语句?,sql-server,sql-server-2008,tsql,Sql Server,Sql Server 2008,Tsql,从我所读到的,我只能在知道要显示的列时使用PIVOT。否则,我必须使用动态sql: select * into #another_table from ( select City, [month], [win-loss] from #final ) src pivot ( min([win-loss]) for month in ([1], [2], [3], [4], [5]) ) piv; 在上面的查询中,([1]、[2]、[3]、[4]、[5])中的月份的指的是月份号,

从我所读到的,我只能在知道要显示的列时使用
PIVOT
。否则,我必须使用动态sql:

select * into #another_table
from 
(
  select City, [month], [win-loss]
  from #final
) src
pivot
(
  min([win-loss])
  for month in ([1], [2], [3], [4], [5])
) piv;
在上面的查询中,([1]、[2]、[3]、[4]、[5])中的月份的
指的是月份号,在这个特定的查询中,
#final
有1-5个月的数据

虽然我不知道如何查询月份,但我知道
month
列最多有12个月

是否可以插入
IF
语句,以便考虑最长12个月的任何可能组合

我不喜欢使用动态sql,除非没有其他选择

#final
看起来像这样。至少在本例中,我知道第1-5个月有行,但月份编号将从此表中检索:

City    month   win-loss
Houston 1       LOSS
Miami   2       WON
Orlando 3       WON
Reading 4       WON

不可能在单个语句中插入IF。避免动态sql的方法如下(psuedocode):


我很确定这将采用动态SQL,但在这种情况下这并不是一件坏事。因为您不接受动态SQL中的任何参数,所以不必担心SQL注入,在这种情况下,动态SQL不会成为性能负担。
IF A = true
  {SELECT Query A}
ELSE IF B = true
  {SELECT Query B}
ELSE IF ...