[英]USING SQL CROSS JOIN
I have a table that holds survey data, two data points are Ethnicity and Flavor_Pref. 我有一个包含调查数据的表,两个数据点是Ethnicity和Flavor_Pref。 The Flavor_Pref hold an integer 1, 2, 3,4,5.
Flavor_Pref保持整数1,2,3,4,5。 1 = Dislike Very Much, 5 Like Very Much.
1 =不喜欢非常多,5喜欢非常多。
Ethnicity Flavor_Pref
African American 3
Caucasian 2
Asian 4
Hispanic 1
African American 3
Caucasian 4
Asian 5
Hispanic 2
African American 4
Caucasian 1
Asian 4
Hispanic 2
African American 3
Caucasian 2
Asian 2
Hispanic 1
I want run a query to get 4 columns, one for each Ethnic group. 我想运行一个查询来获得4列,每个族群一个。 Each group has a different number of responses.
每个组都有不同数量的回复。
This is what I'm working on: I get over 1M results.... I only have 400 surveys. 这就是我正在做的事情:我获得了超过1M的结果......我只有400个调查。
select AA.Flavor_Pref as AA,H.Flavor_Pref as H,C.Flavor_Pref AS C,
A.Flavor_Pref AS A from
(SELECT ETHNICITY,Flavor_Pref FROM FLAVORS WHERE ETHNICITY = 'AFRICAN AMERICAN')AS AA
CROSS JOIN
(SELECT ETHNICITY,Flavor_Pref FROM FLAVORS WHERE ETHNICITY = 'HISPANIC') AS H
CROSS JOIN
(SELECT ETHNICITY,Flavor_Pref FROM FLAVORS WHERE ETHNICITY = 'CAUCASIAN') AS C
CROSS JOIN
(SELECT ETHNICITY,Flavor_Pref FROM FLAVORS WHERE ETHNICITY = 'ASIAN' ) AS A
What I'm looking for is: In this case there are fewer Hispanic results, so nothing is reported. 我正在寻找的是:在这种情况下,西班牙裔结果较少,因此没有任何报道。
African Americans Hispanic Caucasian Asian
3 1 2 4
3 2 4 5
4 2 1 5
. . . .
. . . .
. . . .
3 2 4
2 1 1
What you are looking for is PIVOT
ing rows in to columns. 你所寻找的是
PIVOT
中列荷兰国际集团行。 Here is the standard way to do this, it will for all the RDBMS: 以下是执行此操作的标准方法,它将适用于所有RDBMS:
SELECT
MAX(CASE WHEN Ethnicity = 'African American' THEN Flavor_Pref END)
AS 'African Americans',
MAX(CASE WHEN Ethnicity = 'Hispanic' THEN Flavor_Pref END)
AS 'Hispanic',
MAX(CASE WHEN Ethnicity = 'Caucasian' THEN Flavor_Pref END)
AS 'Caucasian',
MAX(CASE WHEN Ethnicity = 'Asian' THEN Flavor_Pref END)
AS 'Asian'
FROM @flavors
GROUP BY Flavor_Pref
You want the most popular flavor for each ethnicity. 你想要每个种族最流行的味道。 You can do this in most databases using the ranking functions:
您可以使用排名功能在大多数数据库中执行此操作:
select max(case when ethnicity = 'African American' and seqnum = 1 then flavor_pref end) as AfricanAmerican,
max(case when ethnicity = 'Hispanic' and seqnum = 1 then flavor_pref end) as Hispanic,
max(case when ethnicity = 'Caucasian' and seqnum = 1 then flavor_pref end) as Caucasian,
max(case when ethnicity = 'Asian' and seqnum = 1 then flavor_pref end) as Asian
from (select t.ethnicity, t.flavor_pref, cnt,
row_number() over (partition by t.enthnicity order by cnt desc) as seqnum
from (select t.ethnicity, t.flavor_pref, count(*) as cnt
from t
group by t.ethnicity, t.flavor_pref
) t
) ts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.