SQL WHERE中的多个AS列

时间:2019-04-24 13:16:53

标签: sql select google-bigquery where

我有一张桌子

name | age | city
-------------
joe | 42 | berlin
ben | 42 | munich
anna | 22 | hamburg
pia | 50 | berlin
georg | 42 | munich
lisa | 42 | berlin

现在我想让所有42岁的人按城市在不同的列中

berlin | munich
-------------
joe | ben
lisa | georg

所以我需要类似

SELECT (
SELECT  name AS berlin WHERE city = "berlin"
UNION
SELECT name AS munich WHERE city = "munich")
FROM TABLE
WHERE
age = 42

柏林最好的 乔尔格

3 个答案:

答案 0 :(得分:0)

我认为您想要汇总:

select max(case when city = 'berlin' then name end) as berlin,
       max(case when city = 'munich' then name end) as munich
from (select t.*, row_number() over (partition by city order by name) as seqnum
      from t
      where city in ('berlin', 'munich') and age = 42
     ) t
group by seqnum
order by seqnum;

答案 1 :(得分:0)

例如,使用PIVOT是通过SQL Server完成的。希望这可以帮到你。

DECLARE @columns varchar(MAX);
DECLARE @sql nvarchar(max)
CREATE TABLE #Table
(
idPerson int,
firstName varchar(10),
age int,
city varchar(10)
);

INSERT INTO #Table
SELECT '1', 'joe', '42','berlin' UNION ALL
SELECT '2', 'ben', '42','munich' UNION ALL
SELECT '3', 'Ana', '22','hamburg' UNION ALL
SELECT '4', 'pia', '50','berlin' UNION ALL
SELECT '5', 'george', '42','munich' UNION ALL
SELECT '6', 'lisa', '42','munich'



--SELECT * from #Table

 SET @columns = STUFF(
 (
 SELECT
   ',' + QUOTENAME(LTRIM(city))
 FROM
   (SELECT DISTINCT city
    FROM #Table
   ) AS T
 ORDER BY
 city
 FOR XML PATH('')
 ), 1, 1, '');

 SET @sql = N'
 SELECT
   * 
  FROM
  (  
  SELECT  idPerson ,firstName ,age ,city 
  FROM #Table
    --WHERE age = 42
  ) AS T
  PIVOT   
  (
  MAX(firstName)
  FOR city IN (' + @columns + N')
  ) AS P order by age;'; 

EXEC sp_executesql @sql;
DROP TABLE #Table;

答案 2 :(得分:0)

感谢您的帮助!根据戈登·林霍夫的答案,我得到了以下解决方案:

选择max(当city ='berlin'然后名称结尾的情况)为柏林,        max(当city ='munich'然后名称结尾的情况)为慕尼黑 从表 年龄= 42 ;