我试图找出如何为州缩写添加别名。
示例:
QUERY:
SELECT DISTINCT CHAPTER, COUNT(CHAPTER)AS MEMBERS
FROM Name
WHERE MEMBER_RECORD = '1'
AND COUNTRY in ('',' ','United States')
AND CHAPTER IN
('AL',
'AK',
'AZ')
我想将完整的州名添加到AL,AK和AZ。
示例:
AND CHAPTER IN
('AL' AS 'ALABAMA',
'AK' AS 'ALASKA',
'AZ' AS 'ARIZONA')
答案 0 :(得分:4)
您可以使用CASE
表达式:
SELECT CASE
WHEN CHAPTER = 'AL' THEN 'ALABAMA'
WHEN CHAPTER = 'AK' THEN 'ALASKA'
WHEN CHAPTER = 'AZ' THEN 'ARIZONA'
END AS CHAPTER,
COUNT(*) AS MEMBERS
FROM Name
WHERE MEMBER_RECORD = '1'
AND COUNTRY in ('',' ','United States')
AND CHAPTER IN ('AL','AK','AZ')
GROUP BY CASE
WHEN CHAPTER = 'AL' THEN 'ALABAMA'
WHEN CHAPTER = 'AK' THEN 'ALASKA'
WHEN CHAPTER = 'AZ' THEN 'ARIZONA'
END;
但我建议你创建一个别名表并用它执行JOIN
:
SELECT A.CHAPTERNAME,
COUNT(*) AS MEMBERS
FROM dbo.Name AS N
LEFT JOIN dbo.Aliases AS A
ON N.CHAPTER = A.CHAPTER
WHERE MEMBER_RECORD = '1'
AND COUNTRY in ('',' ','United States')
AND CHAPTER IN ('AL','AK','AZ')
GROUP BY A.CHAPTERNAME;