SQL查询:如何获取每个地址的地址列表和订单数量

时间:2015-04-06 10:20:18

标签: sqlite

我有两张桌子

一个包含用户地址列表,另一个表包含订单列表。

我想要做的是加入表格,获取一份明确的地址列表和地址的订单数量。

Table1
ID    - USERNAME    - USERADDRESS
1     - USER1       - ADRESS1
2     - USER2       - ADDRES2
3     - USER3       - ADDRES3

Table2
ID    - USERID      - ORDERDETAIL
1     - 3           - ...
2     - 2           - ...
3     - 2           - ...
4     - 1           - ...
5     - 3           - ...
6     - 2           - ...
7     - 1           - ...
8     - 3           - ...
9     - 3           - ...
10    - 3           - ...

获取

ADDRESS1   2
ADDRESS2   3
ADDRESS3   5

如何在一个SQL语句中执行此操作?

2 个答案:

答案 0 :(得分:1)

根据评论,您应该说明RDBMS并发布您的尝试。加入和应用聚合的一般方法是这样的:

SELECT t1.USERADDRESS, 
       COUNT(t2.ID) as NumOrders -- Show each address and a count of orders
FROM Table1 t1
   INNER JOIN Table2 t2
   on t2.USERID = t1.ID -- JOIN Key
GROUP BY t1.USERADDRESS;

答案 1 :(得分:1)

您可以查看此查询:

select a.address, count(o.order_num) orders from addresses a inner join orders o on a.address_id = o.address_id GROUP BY a.address