我有
select CustID,
case permission
When 'read' then 'X'
end as 'Read',
case permission
when 'write' then 'X'
end as 'Write',
case permission
when 'own' then 'X'
end as 'Own',
case permission
when ‘destroy’ then ‘X’
end as ‘Destroy’
from rights
group by custID, permission
我只想为每个custID添加一行。相反,我得到:
CustID | Read | Write | Own | Destroy
208345482 X NULL NULL NULL|
208345482 NULL NULL X NULL|
208345482 NULL NULL NULL X|
208345482 NULL X NUL NULL|
8093657522 NULL NULL NULL X|
8093657522 NULL NULL X NULL|
我试图通过别名子查询进行分组无济于事。任何帮助将不胜感激。
答案 0 :(得分:3)
您无法在GROUP BY
中使用别名,因为在应用别名之前会对其进行解析。您可以使用别名的唯一位置是ORDER BY
子句,因为它是在SELECT
之后解析的唯一子句,其中定义了别名。
典型的解决方法是重复GROUP BY
子句中的表达式:
SELECT x = CASE ... END, SUM(something)
FROM dbo.somewhere
GROUP BY CASE ... END;
或使用CTE:
;WITH src AS
(
SELECT x = CASE ... END, something
FROM dbo.somewhere
)
SELECT x, SUM(something)
FROM src
GROUP BY x;
或使用子查询:
SELECT x, SUM(something)
FROM
(
SELECT x = CASE ... END, something
FROM dbo.somewhere
) AS src
GROUP BY x;
这些都应该同样优化,但您应该测试您的具体方案以确定。
在您的情况下,您可以按如下方式编写:
SELECT CustID,
[Read] = MAX(CASE permission WHEN 'read' THEN 'X' END),
[Write] = MAX(CASE permission WHEN 'write' THEN 'X' END),
[Own] = MAX(CASE permission WHEN 'own' THEN 'X' END),
[Destroy] = MAX(CASE permission WHEN 'destroy' THEN 'X' END)
FROM dbo.rights
GROUP BY custID;
或者像这样:
SELECT CustID,
MAX([Read]), MAX([Write]), MAX([Own]), MAX([Destroy])
FROM
(
SELECT CustID,
[Read] = CASE permission WHEN 'read' THEN 'X' END,
[Write] = CASE permission WHEN 'write' THEN 'X' END,
[Own] = CASE permission WHEN 'own' THEN 'X' END,
[Destroy] = CASE permission WHEN 'destroy' THEN 'X' END
FROM dbo.rights
) AS src
GROUP BY custID;
请不要使用单引号来分隔列或表'alias'
。语法不仅被弃用,而且还使实体看起来像字符串文字。如果必须对其进行转义(例如,如果选择错误的列名称),请使用[square brackets]
。
答案 1 :(得分:0)
您可以使用PIVOT
表运算符直接在一个查询中执行此操作,而不是使用这些CASE
表达式。
它将执行您正在寻找的进一步步骤,即使用CASE
表达式传播后的记录分组。类似的东西:
SELECT
CustId,
read,
write,
own,
Destroy
FROM
(
SELECT custid, permission, x
FROM tablename
) AS t
PIVOT
(
MAX(x)
FOR permission IN('read',
'write',
'own',
'Destroy')
) AS p;
在您的查询中,如果x
是一个字符串文字而不是标识符,那么您可以选择它作为字符串文字,在锚点查询SELECT custid, permission, 'x' AS x FROM tablename
中使用别名,那么上面的查询应该有效细