SQL Server ...在两个IF条件下联合所有

时间:2016-11-29 12:56:11

标签: sql sql-server

我有两个表值函数,我需要做一些选择... 我试图在那个选择上做UNION,但是我不能做"联合所有"我的IF ... 如果条件,它应该返回一行和两列... 此代码应返回:

September | 50

October   | 33

我该怎么做?!

这是我的代码:

IF (select TotalTreinos from dbo.tbl_CALCULA_TREINOS_MES('20160901','20160930',2,5)) = (SELECT Presencas FROM DBO.tbl_CALCULA_PRESENCAS('Setembro',9,2)) 
    SELECT 'Setembro' as Mes, 100 AS PercentPresencas
else
    select 'Setembro' as Mes, (((SELECT Presencas FROM DBO.tbl_CALCULA_PRESENCAS('Setembro',9,2)) * 100) / (select TotalTreinos from dbo.tbl_CALCULA_TREINOS_MES('20160901','20160930',2,5))) as PercentPresencas

union all

IF (select TotalTreinos from dbo.tbl_CALCULA_TREINOS_MES('20161001','20161031',2,5)) = (SELECT Presencas FROM DBO.tbl_CALCULA_PRESENCAS('Outubro',10,2)) 
    SELECT 'Outubro' as Mes, 100 AS PercentPresencas
else
    select 'Outubro' as Mes,(((SELECT Presencas FROM DBO.tbl_CALCULA_PRESENCAS('Outubro',10,2)) * 100) / (select TotalTreinos from dbo.tbl_CALCULA_TREINOS_MES('20161001','20161031',2,5))) as PercentPresencas

1 个答案:

答案 0 :(得分:1)

T-SQL中的IF语句是命令式语句,不是SQL语言的一部分。您要做的是将IF语句移到查询中,而应该使用CASE代替:

SELECT 
  'Setembro' AS Mes, 
  CASE WHEN (SELECT TotalTreinos FROM dbo.tbl_CALCULA_TREINOS_MES('20160901','20160930',2,5)) 
          = (SELECT Presencas FROM DBO.tbl_CALCULA_PRESENCAS('Setembro',9,2)) 
       THEN 100
       ELSE (((SELECT Presencas FROM DBO.tbl_CALCULA_PRESENCAS('Setembro',9,2)) * 100) 
            / (SELECT TotalTreinos FROM dbo.tbl_CALCULA_TREINOS_MES('20160901','20160930',2,5)))
  END AS PercentPresencas
UNION ALL
SELECT 
  'Outubro' AS Mes, 
  CASE WHEN (SELECT TotalTreinos FROM dbo.tbl_CALCULA_TREINOS_MES('20161001','20161031',2,5)) 
          = (SELECT Presencas FROM DBO.tbl_CALCULA_PRESENCAS('Outubro',10,2)) 
       THEN 100
       ELSE (((SELECT Presencas FROM DBO.tbl_CALCULA_PRESENCAS('Outubro',10,2)) * 100) 
            / (SELECT TotalTreinos FROM dbo.tbl_CALCULA_TREINOS_MES('20161001','20161031',2,5))) 
  END AS PercentPresencas

通过分解常用表达式进一步改进CTE:

WITH 
  t1 (Mes, StartDate, EndDate) AS (
    -- Of course, these could be calculated also automatically, but you get the idea...
    SELECT 'Setembro', '20160901', '20160930'
    UNION ALL
    SELECT 'Outubro', '20161001', '20161031'
  ), 
  t2 (Mes, TotalTreinos, Presencas) AS (
    SELECT
      Mes,
      (SELECT TotalTreinos FROM dbo.tbl_CALCULA_TREINOS_MES(StartDate,EndDate,2,5)),
      (SELECT Presencas FROM DBO.tbl_CALCULA_PRESENCAS(Mes,10,2))
    FROM t1
  )
SELECT 
  Mes, 
  CASE WHEN TotalTreinos = Presencas
       THEN 100
       ELSE Presencas * 100 / TotalTreinos
  END AS PercentPresencas
FROM t2