在SQL Server中使用If else条件的All All

时间:2016-10-12 11:17:34

标签: sql-server sql-server-2012

我正在尝试使用union all with If else条件我的查询在

之下
DECLARE @Date DATE = '2016-03-25'
SELECT DATEPART(WEEK, @date)
IF (DATEPART(WEEK, @date) <= 13)
  BEGIN
    SELECT
      count(ip),
      datepart(YEAR, crn_dt)
    FROM C_User_Profile
    WHERE DATEPART(WEEK, C_User_Profile.crn_dt) BETWEEN 0 AND 13
    GROUP BY datepart(YEAR, crn_dt)
  END
ELSE
  BEGIN
    PRINT 0
  END
    UNION ALL
IF (DATEPART(WEEK, @date) > 13 AND DATEPART(WEEK, @date) <= 26)
  BEGIN
    SELECT
      count(ip),
      datepart(YEAR, crn_dt)
    FROM C_User_Profile
    WHERE DATEPART(WEEK, C_User_Profile.crn_dt) BETWEEN 14 AND 26
    GROUP BY datepart(YEAR, crn_dt)
  END
ELSE
  BEGIN
    PRINT 0
  END
    UNION ALL
IF (DATEPART(WEEK, @date) > 26 AND DATEPART(WEEK, @date) <= 39)
  BEGIN
    SELECT
      count(ip),
      datepart(YEAR, crn_dt)
    FROM C_User_Profile
    WHERE DATEPART(WEEK, C_User_Profile.crn_dt) BETWEEN 27 AND 39
    GROUP BY datepart(YEAR, crn_dt)
  END
ELSE
  BEGIN
    PRINT 0
  END
    UNION ALL
IF (DATEPART(WEEK, @date) > 39)
  BEGIN
    SELECT
      count(ip),
      datepart(YEAR, crn_dt)
    FROM C_User_Profile
    WHERE DATEPART(WEEK, C_User_Profile.crn_dt) BETWEEN 40 AND 54
    GROUP BY datepart(YEAR, crn_dt)
  END
ELSE
  BEGIN
    PRINT 0
  END

因为我需要显示所有结果所以我使用if all条件但是我收到错误显示联盟附近的语法错误请帮助我

2 个答案:

答案 0 :(得分:2)

这不是SQL SERVER

中的有效语法

这是一种方式

SELECT Count(CASE
               WHEN Datepart(week, C_User_Profile.crn_dt) BETWEEN 0 AND 13
                    AND Datepart(week, @date) <= 13 THEN 1
               WHEN Datepart(week, C_User_Profile.crn_dt) BETWEEN 0 AND 13
                    AND Datepart(week, @date) > 13
                    AND Datepart(week, @date) <= 26 THEN 1
               WHEN Datepart(week, C_User_Profile.crn_dt) BETWEEN 27 AND 39
                    AND Datepart(week, @date) > 26
                    AND Datepart(week, @date) <= 39 THEN 1
               WHEN Datepart(week, C_User_Profile.crn_dt) BETWEEN 40 AND 54
                    AND Datepart(week, @date) > 39 THEN 1
             END),
       Datepart(year, crn_dt)
FROM   C_User_Profile
WHERE  Datepart(week, C_User_Profile.crn_dt) BETWEEN 0 AND 54
GROUP  BY Datepart(year, crn_dt) 

答案 1 :(得分:0)

这可能有效

script(src='/javascripts/leaflet.markercluster-src.js')