因此,在按年和月累计所有结果时遇到问题
所以我加入了四个表来提出我的结果
我有一个Customer
表:
Cust_id , f_name , L_name
Products
表:
Product_id, retail_price , cost_price
Orders
表:
Order id, order_date,Cust_id,
Order_details
表:
Order_id Product_id, Quantity,
这就是我现在的查询方式
SELECT
C.FNAME,C.LNAME,
SUM (P.RETAILPRICE * OD.QUANTITY) AS "Total $ spent by Customer",
DATENAME(yyyy,o.ORDER_DATE) AS YEAR,
DATENAME(MM,o.ORDER_DATE) AS MONTH
FROM
ORDER_DETAILS OD
JOIN
PRODUCTS P ON OD.PRODUCT_ID = P.PRODUCT_ID
JOIN
ORDERS O ON O.ORDER_ID = OD.ORDER_ID
JOIN
CUSTOMER C ON C.CUST_ID = O.CUST_ID
GROUP BY
O.ORDER_DATE, C.FNAME,C.LNAME
ORDER BY
DATENAME(yyyy, o.ORDER_DATE), DATENAME(MM, o.ORDER_DATE)
此查询返回如下结果:
customer sum spend yr month
--------------------------------------
Bob Johnson 400.00 2010 jan
Kevin Cruz 123.10 2010 jan
Emily Sheily 74.12 2010 jan
Lily Phantom 475.95 2010 jan
Kevin Cruz 148.52 2010 jan
我希望凯文克鲁兹的订单能够加入到2010年1月的一笔款项中。
我的结果发生了。那年克鲁兹在那个月做了两个订单,但我似乎无法将它们加起来。
我该怎么做?
答案 0 :(得分:0)
您不希望order_date
中有group by
。你想要一年又一个月:
SELECT C.FNAME,C.LNAME,
SUM(P.RETAILPRICE * OD.QUANTITY) AS "Total $ spent by Customer",
DATENAME(year, o.ORDER_DATE) AS YEAR,
DATENAME(month, o.ORDER_DATE) AS MONTH
FROM ORDER_DETAILS OD JOIN PRODUCTS
P
ON OD.PRODUCT_ID = P.PRODUCT_ID JOIN
ORDERS O
ON O.ORDER_ID = OD.ORDER_ID JOIN
CUSTOMER C
ON C.CUST_ID = O.CUST_ID
GROUP BY DATENAME(year, o.ORDER_DATE), DATENAME(month, o.ORDER_DATE), C.FNAME,C.LNAME
ORDER BY DATENAME(year, o.ORDER_DATE),
DATENAME(month, o.ORDER_DATE);