我在SQL中有Product表像这样:
productID Type Amount
1046 1 4
1046 1 5
1046 2 10
1047 1 5
1047 2 3
如何进行查询,输出如下:
productID Type TotalTypeAmount TotalPerProductID
1046 1 9 19
1046 2 10 19
1047 1 5 8
1047 2 3 8
答案 0 :(得分:1)
这样我们也可以做到
rest:
response: RESPONSE
@RestController
public class MyController {
@Value("${rest.response}")
private String restResponse;
@GetMapping("/foo")
public ResponseEntity<String> register() {
return restResponse;
}
}
答案 1 :(得分:1)
更紧凑/专业的方式,也应该更快,因为它不需要加入:
SELECT
productID,
Type,
SUM(Amount) AS TotalTypeAmount,
SUM(SUM(Amount)) OVER (PARTITION BY productID) as TotalPerProduct
FROM
Product
GROUP BY
productID,Type
答案 2 :(得分:0)
如果您使用的是SQL Server或Postgres,则以下内容应该有效:
WITH CTE
AS
(
SELECT
productID,
SUM(Amount) AS TotalAllType
FROM Product
GROUP BY productID
)
SELECT
productID,
Type,
SUM(Amount) AS TotalTypeAmount
,TotalAllType
FROM Product AS P
LEFT JOIN CTE ON CTE.productID=P.productID
GROUP BY productID,Type, TotalAllType;