我已经使用这个论坛一段时间来找到一些SQL相关问题的答案。现在是时候提出一个我试图弄清楚的问题了。
我有两张桌子(产品和来源)。
我想创建一个SQL SELECT来从源中检索记录列表,从产品中检索一个额外的记录(价格的总和)。我希望看到的表应该是这样的:
source.source_id | source.location | source.source_name | source.source_description | source.source_date | source.price | SUM(product.price)| SUM(product.price)WHERE product.quantity< 1(最后一栏是我被卡住的地方)。
source.location和product.location是链接的。
此代码有效并提供我想要的结果:
SELECT s.source_id
, s.location
, s.source_name
, s.source_description
, s.source_date
, s.source_price
, p2.Total
, sum(p1.price) as SumProductSold
FROM source s
JOIN product p1
on s.location = p1.location
JOIN
(
SELECT location, sum(price) as Total
FROM product
GROUP BY location
) p2
on s.location = p2.location
WHERE p1.quantity < 1
GROUP BY s.source_id, s.location, s.source_name
, s.source_description, s.source_date, s.source_price, p2.Total
谢谢bluefeet !!
答案 0 :(得分:4)
没有很多细节你可以做这样的事情:
SELECT s.source_id
, s.location
, s.source_name
, s.source_description
, s.source_date
, s.price
, sum(p.price) as SumProductPrice
, sum(p.location) as SumProductLocation
FROM source S
JOIN product p
on S.location = p.location
WHERE p.quantity < 1
GROUP BY s.source_id, s.location, s.source_name
, s.source_description, s.source_date, s.price
如果您发布更多详细信息,则可以对查询进行微调。
编辑:
您可以再次加入产品表以获取该位置的总数:
SELECT s.source_id
, s.location
, s.source_name
, s.source_description
, s.source_date
, s.price
, sum(p1.price) as SumProductPrice
, p2.Total
FROM source S
JOIN product p1
on S.location = p1.location
JOIN
(
SELECT location, sum(price) as Total
FROM product
WHERE quantity < 1
GROUP BY location
) p2
on S.location = p2.location
WHERE p1.quantity < 1
GROUP BY s.source_id, s.location, s.source_name
, s.source_description, s.source_date, s.price, p2.Total
答案 1 :(得分:0)
我不确定我是否完全理解你的表格结构,但这样的事情应该有效:
Select source.source_id,
source.location,
source.source_name,
source.source_description,
source.source_date,
source.price,
sum(production.location)
from source, product
where source.location = production.location
and location < 0
group by source.source_id,
source.location,
source.source_name,
source.source_description,
source.source_date,
source.price
答案 2 :(得分:0)
从我收集的内容中你想要这样的东西:
SELECT source.source_id,
source.location,
source.source_name,
source.source_description,
source.source_date,
source.price,
SUM(product.price) AS Price1,
SUM(CASE WHEN product.quantity < 1 THEN product.price ELSE 0 END) AS Price2
FROM Source
INNER JOIN Product
ON Product.Location = Source.Location
GROUP BY
source.source_id,
source.location,
source.source_name,
source.source_description,
source.source_date,
source.price