将Access SQL语句转换为T-SQL

时间:2013-08-14 11:30:11

标签: sql-server-2008 ms-access if-statement translate

我有以下代码,我使用Access DB生成,我需要将其翻译为 T-SQL,主要是在IIF语句上出错

SELECT dbo.casyAgeGroups.Sequence, dbo.casyAgeGroups.Description, 
Sum(IIf([gender]='Male' And [age]>=[startage] And [age]<=[endage],1,0)) AS Male, 
Sum(IIf([gender]='Female' And [age]>=[startage] And [age]<=[endage],1,0)) AS Female

 FROM dbo.casyAgeGroups, [qryStats-AgeGenderProfileDetails]
GROUP BY dbo.casyAgeGroups.Sequence, 
         dbo.casyAgeGroups.Description, 
         [qryStats-AgeGenderProfileDetails].EntityType
HAVING ((([qryStats-AgeGenderProfileDetails].EntityType)=0));

2 个答案:

答案 0 :(得分:2)

您应该使用CASE而不是IIF。并将HAVING更改为WHERE语句。

SELECT dbo.casyAgeGroups.Sequence, dbo.casyAgeGroups.Description, 
Sum(CASE 
       WHEN ([gender]='Male' And [age]>=[startage] And [age]<=[endage] 
            THEN 1 ELSE 0 END) AS Male, 
Sum(CASE 
       WHEN ([gender]='Female' And [age]>=[startage] And [age]<=[endage] 
            THEN 1 ELSE 0 END) AS Female

 FROM dbo.casyAgeGroups, [qryStats-AgeGenderProfileDetails]
 WHERE  ((([qryStats-AgeGenderProfileDetails].EntityType)=0))
 GROUP BY dbo.casyAgeGroups.Sequence, 
         dbo.casyAgeGroups.Description, 
         [qryStats-AgeGenderProfileDetails].EntityType

同样,只要您使用HAVING条件EntityType=0,您就不需要按此字段进行分组:

SELECT dbo.casyAgeGroups.Sequence, dbo.casyAgeGroups.Description, 
Sum(CASE 
       WHEN ([gender]='Male' And [age]>=[startage] And [age]<=[endage] 
            THEN 1 ELSE 0 END) AS Male, 
Sum(CASE 
       WHEN ([gender]='Female' And [age]>=[startage] And [age]<=[endage] 
            THEN 1 ELSE 0 END) AS Female

 FROM dbo.casyAgeGroups, [qryStats-AgeGenderProfileDetails]
 WHERE  ((([qryStats-AgeGenderProfileDetails].EntityType)=0))
 GROUP BY dbo.casyAgeGroups.Sequence, 
         dbo.casyAgeGroups.Description 

答案 1 :(得分:0)

使用CASE statement

这样的东西
SELECT  dbo.casyAgeGroups.Sequence, 
        dbo.casyAgeGroups.Description, 
        Sum(CASE WHEN [gender]='Male' And [age]>=[startage] And [age]<=[endage] THEN 1 ELSE 0 END) AS Male, 
        Sum(CASE WHEN [gender]='Female' And [age]>=[startage] And [age]<=[endage] THEN 1 ELSE 0 END)) AS Female
FROM    dbo.casyAgeGroups, 
        [qryStats-AgeGenderProfileDetails]
GROUP BY    dbo.casyAgeGroups.Sequence, 
            dbo.casyAgeGroups.Description, 
            [qryStats-AgeGenderProfileDetails].EntityType
HAVING  [qryStats-AgeGenderProfileDetails].EntityType=0