我有3个表1)用户(userId,年龄)2)购买(purchaseId,userId,itemId,date)3)项目(itemId,price)。目标是编写一个查询,以显示按月分组的每个用户的平均购买金额。我目前还不确定我是否需要第一张桌子,到目前为止,我已经这样了:
SELECT Purchases.userid, Purchases.date, Purchases.itemId Items.itemId, AVG(SUM(Items.price))
FROM Purchases
INNER JOIN Purchases.itemId ON Items.itemId
GROUP BY (somehow group by month)
我被困住了。你能解释一下,如何编写这样的查询。很抱歉,我没有表的示例或正确的输出示例,因为它是一个测试任务。谢谢!
答案 0 :(得分:1)
在SQL Server中:
{
"fields": {
"project": {
"key": "MFS"
},
"summary": "Test Jira Integration API --Testing New XtremeJira Interface",
"description": "DonTest Jira Integration API ",
"issuetype": {
"name": "Defect"
},
"fixVersions": [{
"name": "MFS 15.1.0"
}, {
"name": "MFS 15.6.2"
}],
"customfield_10182": "1002",
"priority": {
"name": "Major",
"id": "3"
},
"versions": [{
"name": "MFS 15.1.0"
}, {
"name": "MFS 15.6.2"
}],
"assignee": {
"name": "kartik"
},
"components": [],
"environment": ""
}}
答案 1 :(得分:1)
你可以试试这个。
SELECT Purchases.userid, MONTH(Purchases.date), AVG(Items.price)
FROM Purchases
INNER JOIN Items ON Purchases.itemId = Items.itemId
GROUP BY Purchases.userid, MONTH(Purchases.date)
答案 2 :(得分:1)
按月分组需要在"桶中添加日期"与该日期相关的年份和月份。每种数据库类型都有它自己独特的功能集,例如
--MS SQL Server
SELECT Purchases.userid, Purchases.itemId, year(Purchases.date), month(Purchases.date), AVG(Items.price)
FROM Purchases
GROUP BY Purchases.userid, Purchases.itemId, year(Purchases.date), month(Purchases.date)
--Oracle
SELECT Purchases.userid, Purchases.itemId, trunc(Purchases.date,'YYYYMM'), AVG(Items.price)
FROM Purchases
GROUP BY Purchases.userid, Purchases.itemId, trunc(Purchases.date,'YYYYMM')
答案 3 :(得分:1)
您不能使用AVG(SUM(Items.price))
因此,您可能成为获得SUM
然后使用AVG
在SQL Server中:
SELECT
Purchases.userid,
YEAR(Purchases.date),
MONTH(Purchases.date),
Purchases.itemId
Items.itemId,
AVG(Items.SumPrice)
FROM
Purchases
INNER JOIN
Users T2 ON Purchases.userId = T2.userId
INNER JOIN
(SELECT
itemId, SUM(price) AS SumPrice
FROM
Items
GROUP BY
itemId) AS Items ON Items.itemId
GROUP BY
Purchases.userid, Purchases.itemId,
YEAR(Purchases.date),
MONTH(Purchases.date),
Items.itemId