创建消除重复 months/year 的 SQL 查询
Creating an SQL query that eliminates duplicate months/year
你好 Stack Overflow 社区 - 希望我在这个问题上走在正确的轨道上,但我正在尝试编写一个查询,其中的报告显示 month/year 所下订单的数量。该报告目前提出了我试图通过 month/year 集体加入他们的所有日子。希望这是有道理的,我对此很陌生,请保持温柔;)
select distinct month(o.orderdate) 'Month',
year(o.orderdate) 'Year', sum(od.Quantity) as Orders
from OrderDetails od
join Products p
on od.ProductID = p.ProductID
join Orders o
on od.OrderID = o.OrderID
group by o.orderdate
Order by year, month asc;
您需要group by
定义每一行。在你的例子中,那是年份和月份:
select year(orderdate) as yyyy, month(o.orderdate) as mm,
sum(od.Quantity) as Orders
from OrderDetails od join
Products p
on od.ProductID = p.ProductID join
Orders o
on od.OrderID = o.OrderID
group by year(o.orderdate), month(o.orderdate)
Order by yyyy, mm asc;
备注:
- 我将列名更改为
yyyy
和 mm
这样它们就不会与保留字 year
和 month
. 冲突
- 不要对列别名使用单引号。这是一个坏习惯,最终会导致您的查询出现问题。
- 我总是使用
as
作为列别名(以帮助防止遗漏逗号错误),但从不使用 table 别名。
- 此查询不需要
product
table。
编辑:如果您想要 订单数 ,您的查询建议,那么这可能更合适:
select year(o.orderdate) as yyyy, month(o.o.orderdate) as mm,
count(*) as Orders
from orders o
group by year(o.orderdate), month(o.orderdate)
Order by yyyy, mm asc;
你必须按月和年分组
select distinct month(o.orderdate) 'Month',
year(o.orderdate) 'Year', sum(od.Quantity) as Orders
from OrderDetails od
join Products p
on od.ProductID = p.ProductID
join Orders o
on od.OrderID = o.OrderID
group by month(o.orderdate), year(o.orderdate)
Order by [Year],[month]
你好 Stack Overflow 社区 - 希望我在这个问题上走在正确的轨道上,但我正在尝试编写一个查询,其中的报告显示 month/year 所下订单的数量。该报告目前提出了我试图通过 month/year 集体加入他们的所有日子。希望这是有道理的,我对此很陌生,请保持温柔;)
select distinct month(o.orderdate) 'Month',
year(o.orderdate) 'Year', sum(od.Quantity) as Orders
from OrderDetails od
join Products p
on od.ProductID = p.ProductID
join Orders o
on od.OrderID = o.OrderID
group by o.orderdate
Order by year, month asc;
您需要group by
定义每一行。在你的例子中,那是年份和月份:
select year(orderdate) as yyyy, month(o.orderdate) as mm,
sum(od.Quantity) as Orders
from OrderDetails od join
Products p
on od.ProductID = p.ProductID join
Orders o
on od.OrderID = o.OrderID
group by year(o.orderdate), month(o.orderdate)
Order by yyyy, mm asc;
备注:
- 我将列名更改为
yyyy
和mm
这样它们就不会与保留字year
和month
. 冲突
- 不要对列别名使用单引号。这是一个坏习惯,最终会导致您的查询出现问题。
- 我总是使用
as
作为列别名(以帮助防止遗漏逗号错误),但从不使用 table 别名。 - 此查询不需要
product
table。
编辑:如果您想要 订单数 ,您的查询建议,那么这可能更合适:
select year(o.orderdate) as yyyy, month(o.o.orderdate) as mm,
count(*) as Orders
from orders o
group by year(o.orderdate), month(o.orderdate)
Order by yyyy, mm asc;
你必须按月和年分组
select distinct month(o.orderdate) 'Month',
year(o.orderdate) 'Year', sum(od.Quantity) as Orders
from OrderDetails od
join Products p
on od.ProductID = p.ProductID
join Orders o
on od.OrderID = o.OrderID
group by month(o.orderdate), year(o.orderdate)
Order by [Year],[month]