0

列出以“NEW”开头的州描述以及位于该州的雇主数量。确保列出所有以“NEW”开头的状态,即使计数为零。确保您的列标题与下面显示的内容相匹配。

+---------------+---------------------+
| Description   | Number of Companies |
+---------------+---------------------+
| NEW HAMPSHIRE |                   0 |
| NEW JERSEY    |                   1 |
| NEW MEXICO    |                   0 |
| NEW YORK      |                  13 |
+---------------+---------------------+ 
4 rows in set (0.00 sec)

对于这个问题,我使用了:

SELECT state.description, COUNT(*) "Number of Commpanies"
FROM employer
WHERE SUBSTR(state.description, 1, INSTR(state.description, 'NEW')-1) AS "Number of Companies";

错误:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'AS "N
umber of Companies"' at line 3

为什么我会得到这个,什么是正确的语法。首先,我不确定我是否正确地遵循了这个问题。表格如下:

mysql> DESCRIBE state;
+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| statecode   | char(2)     |      | PRI |         |       |
| description | varchar(30) |      |     |         |       |
+-------------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec) mysql>

mysql>SELECT * FROM 雇主

| companyname                    | division         | address                   | city             | statecode | zipcode |
| Acme Information Source        | Customer Support | 132 Commerical Way        | Cleveland        | OH        |   44234 |
| Ajax Software, Inc.            | RandD            | 2421 West Industrial Way  | Berkeley         | CA        |   94710 |
| Ajax Software, Inc.            | Production       | 2421 West Industrial Way  | Berkeley         | CA        |   94710 |
4

4 回答 4

0

列别名的正确语法是:

SELECT state.description, COUNT(*) AS "Number of Companies"
FROM employer
WHERE .. -- your logic here

您不能在 WHERE 之后添加列别名,这没有意义。

但是,您有办法去实际回答这个问题。例如,您引用了该state表,但尚未加入该表。

于 2013-08-07T00:27:47.463 回答
0

where 子句必须类似于

where something = something

你的很像

where something as alias name

但是,简单的答案是:

where state.description like 'NEW%'
于 2013-08-07T00:29:55.690 回答
0

尝试以下操作:

SELECT s.description, count(e.*) as "Number of Companies"
  FROM employer e left join state s on e.statecode = s.statecode 
 WHERE s.description like 'NEW%'
 GROUP by 1
于 2013-08-07T03:06:18.510 回答
0

使用 JOIN,而您缺少 GROUP BY

SELECT
   s.description,
   COUNT(*) AS "Number of Companies"
FROM state a
JOIN employer e ON s.statecode = e.statecode
WHERE s.description LIKE 'NEW%'
GROUP BY 1
于 2013-08-07T02:32:54.893 回答