开发者

SQL subqueries - which order do you perform the SELECT statements?

I just started learning SQL a couple of days ago, and I'm trying to understand which order I should use the SELECT statement when building subqueries. Here is a simple example of what I am trying to accomplish.

I have two tables - One that specifies the demographics of a customer list, and the other that details how they heard about our company.

In the first table, my customers are listed as either Male or Female in the Gender column, and then in the next column, their ethnicity is specified (Caucasian, African American, Hispanic, etc).

In the second table, there is a Referral column that specifies how they heard about our company (TV, radio, website, etc).

I want to first filter the customers by gender (I want to show only Female data), and then I want to count how many times our customers found us through our website for each ethnicity listed in the table.

SELECT Ethnicity, COUNT(Referral)
FROM Demographics, Marketing
WHERE Demographics.id = Marketing.source_id
AND Referral = 'website'
/* confused about how to put subquery here saying Gender = 'Female' */
ORDER BY Ethnicity

Basically, I'm confused about how to 开发者_运维百科properly include the subquery and if I am even filtering in the correct order.

But here is what I want my table to look like:

/*Data is shown for ONLY Females */

Referral        Caucasian     African American       Hispanic      Asian

website          7             19                     14            22

I'm sorry, this code is probably really messed up. Please help if you can.


From what you've described, you don't need a subquery:

SELECT Ethnicity, COUNT(Referral)
FROM Demographics, Marketing
WHERE Demographics.id = Marketing.source_id
AND Referral = 'website'
AND Gender = 'Female'
ORDER BY Ethnicity

...note that this gives you a different resultset from the one you've shown, though, with ethnicity, count on each row.


When you are using two table u must use the INNER JOIN syntax: http://w3schools.com/sql/sql_join_inner.asp

    SELECT Ethnicity, COUNT(Referral)
    FROM Demographics INNER JOIN Marketing
    ...
    AND Referral = 'website'
    AND Gender = 'Female'
    ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜