我有三个表:Cutomers,Orders和Items,其中包含一些数据
表:项目
Id Name Order_Id price
----------------------------------
1 Item1 1 10
2 Item2 1 20
3 Item3 2 30
4 Item4 2 40
5 Item5 3 50
6 Item6 3 60
7 Item7 4 70
8 Item8 5 80
9 Item9 5 90
表:订单
Id Customer_Id
----------------------
1 1
2 1
3 2
4 2
5 3
-----------------------
表:客户
Id Name
------------------------
1 Alex
2 John
3 Mark
-------------------------
我希望SQl查询输出结果为
------------------------------------------
Name Total Total Total
Order Orders Items
Price
--------------------------------------------
Alex 100 2 4
John 180 2 3
Mark 170 1 2
----------------------------------------
我尝试使用以下查询>>>>>>>>>>>>>
Select c.Name, SUM(i.price) as 'Total Order Price', COUNT(o.Id) as
'Total Orders' ,COUNT(i.id) as 'Total Items'
from Customers c
left join Orders o
on o.Customer_Id=c.Id
left join Items i
on i.Order_Id=o.Id
group by c.Name
Out Put:>>>>>>>>>>>>>>
Name Total Total Total
Order Orders Items
Price
--------------------------------------------
Alex 100 4 4
John 180 3 3
Mark 170 2 2
----------------------------------------
答案 0 :(得分:0)
对于您的查询,最简单的解决方案是使用Date tgl = rs.getDate("Tanggal_Lahir");//take from database
Date kini = new Date();
int umur = kini.getYear()-tgl.getYear();//.getyear have strikethrough
:
count(distinct)
不要使用单引号作为列别名。这会引起混淆,因为它仅适用于Select c.Name, SUM(i.price) as TotalOrderPrice,
COUNT(DISTINCT o.Id) as TotalOrders,
COUNT(i.id) as TotalItems
from Customers c left join
Orders o
on o.Customer_Id = c.Id left join
Items i
on i.Order_Id = o.Id
group by c.Name ;
之后的select
。将列命名为不需要转义字符的字符串,或者为数据库使用适当的转义字符(通常是双引号,方括号或后标记)。
答案 1 :(得分:0)
我建议使用下面的查询,它只使用内连接而不是左连接:
SELECT c.name, SUM(i.price), COUNT(DISTINCT order_id), COUNT(DISTINCT i.id)
FROM items i
JOIN orders o ON i.order_id = o.id
JOIN customers c ON c.id = o.customer_id
GROUP BY c.name;
我希望它有所帮助。