1

我有以下代码,我使用 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));
4

2 回答 2

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 
于 2013-08-14T11:34:50.513 回答
0

使用CASE 语句

就像是

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
于 2013-08-14T11:33:40.310 回答