我有两张桌子:
use exercise;
create table Companies
(
ID int,
Name varchar(100),
City varchar(100),
c_size varchar(100),
PRIMARY KEY (ID)
);
insert into Companies(ID, Name, city, company_size)
values
(222, 'Karma LLC','CITY2', 'big'),
(223, 'Manny Ind.','CITY1', 'medium'),
(224, 'Random PLC','CITY1', 'medium'),
(225, 'Hijack LLC','CITY1', 'medium'),
(226, 'Travels LLC','CITY1', 'small'),
(227, 'Mirana Ind.','CITY2', 'small'),
(228, 'Polla Ind.','CITY3', 'small'),
(229, 'Americano LLC','CITY3', 'small'),
(230, 'Macaroni LLC','CITY4', 'small');
CREATE TABLE INVOICES
(
ID INT auto_increment,
`DATE` DATE,
Company INT,
Amount DECIMAL(7,2),
PRIMARY KEY (ID)
);
INSERT INTO INVOICES(`DATE`,Company,Amount)
VALUES
('2014-01-02', 222, 19500.00),
('2014-01-02', 222, 29205),
('2014-01-07', 222, 152.50),
('2014-01-07', 223, 6590),
('2014-01-07', 223, 4999),
('2014-01-09', 224, 720.60),
('2014-01-09', 225, 1100),
('2014-02-05', 226, 885),
('2014-02-05', 222, 9678.7);
我的任务很简单:编写查询,返回城市支付大部分发票的公司(按金额值)。
我觉得有必要使用JOIN
和表格或其他类似的别名,但我在MySQL
中很新鲜,并且对语言的这些方面有点困惑。寻找好的教程/练习。
然后,查询应该返回如下内容:
|---sum(amount)_for_city_which_paid_most---|---name_of_the_city---|
|------------------number------------------|---------city---------|
对不起ASCII,但我觉得这是明确而快速的方式来表达我的意思
我也想知道查询哪个列出了来自这个城市的公司支付的city_name和金额(如上所述,但是所有城市,而不仅仅是一个)。
抱歉英语不好:(
答案 0 :(得分:0)
那么,这样的事情呢?
SELECT *,SUM(i.Amount) AS total_amount
FROM Companies c
JOIN INVOICES i ON c.ID=i.Company
GROUP BY c.City
ORDER BY total_amount desc
LIMIT 1
编辑:第二个不起作用,因为你想按城市分组,只存在于公司表中。
如果您只是在公司ID之后,您可以为自己保存一个加入:
SELECT i.Company,SUM(i.Amount) AS total_amount
FROM INVOICES i
GROUP BY i.Company
ORDER BY total_amount desc
LIMIT 1
答案 1 :(得分:0)
以下是查询:
SELECT SUM(Amount), city
FROM INVOICES, Companies c
WHERE Company=c.ID
GROUP BY city
ORDER BY SUM(Amount) DESC
LIMIT 1