有以下疑问
--10/24/24 - UNIT PRICE AND QTY SHIPPED
SELECT DBO.SHIPPER.PACKLIST_ID, dbo.shipper.SHIPPED_DATE, DBO.SHIPPER.CUST_ORDER_ID, dbo.SHIPPER_LINE.SHIPPED_QTY, dbo.SHIPPER_LINE.UNIT_PRICE,
dbo.SHIPPER_LINE.SHIPPED_QTY * dbo.SHIPPER_LINE.UNIT_PRICE AS TOTAL
FROM DBO.SHIPPER
INNER JOIN dbo.SHIPPER_LINE on dbo.SHIPPER.PACKLIST_ID = dbo.SHIPPER_LINE.PACKLIST_ID
WHERE dbo.shipper.SHIPPED_DATE BETWEEN dateadd(m, datediff(m, 0, GetDate()), 0) AND dateadd(m, datediff(m, -1, GetDate()), 0)
ORDER BY dbo.shipper.SHIPPED_DATE
返回以下结果(为了讨论而缩写)
PACKLIST_ID DATE CUST_ORDER_ID TOTAL
57976 2024-10-01 C24807 3710.0000000000
57979 2024-10-01 C24860 130.0000000000
58104 2024-10-01 C24941 375.0000000000
58104 2024-10-01 C24941 1925.0000000000
58104 2024-10-01 C24941 0.0000000000
58104 2024-10-01 C24941 0.0000000000
58104 2024-10-01 C24941 0.0000000000
58104 2024-10-01 C24941 0.0000000000
58153 2024-10-04 C24923 780.0000000000
58152 2024-10-07 C24923 -6240.0000000000
我想要的是
PACKLIST_ID DATE CUST_ORDER_ID TOTAL
57976 2024-10-01 C24807 3710.0000000000
57979 2024-10-01 C24860 130.0000000000
58104 2024-10-01 C24941 2300.0000000000
58153 2024-10-04 C24923 780.0000000000
58152 2024-10-07 C24923 -6240.0000000000
如何获得每个
CUST_ORDER_ID
的总和?有时 CUST_ORDER_ID
相同,但 PACKLIST_ID
不同,需要将它们分开。
在这里您可以使用
Group By
功能。
举个简单的例子:
Orders
id item cust_id amount
1 Keyboard 4 450
2 Mouse 4 300
3 Monitor 3 12000
4 Keyboard 1 400
5 Mousepad 2 250
6 Mouse 4 120
7 Mousepad 4 260
8 Keyboard 1 410
9 Monitor 4 11260
在这里我必须找到同一客户的商品总和。
所以这将是上述问题的解决方案:
SELECT order_id, item, sum(amount) as Total, cust_id
FROM Orders
group by
item,
cust_id;
在您的情况下,您可以修改您的查询如下:
SELECT
DBO.SHIPPER.PACKLIST_ID,
dbo.shipper.SHIPPED_DATE,
DBO.SHIPPER.CUST_ORDER_ID,
dbo.SHIPPER_LINE.SHIPPED_QTY,
dbo.SHIPPER_LINE.UNIT_PRICE,
SUM(dbo.SHIPPER_LINE.SHIPPED_QTY * dbo.SHIPPER_LINE.UNIT_PRICE) AS TOTAL
FROM
DBO.SHIPPER
INNER JOIN
dbo.SHIPPER_LINE on dbo.SHIPPER.PACKLIST_ID = dbo.SHIPPER_LINE.PACKLIST_ID
WHERE
dbo.shipper.SHIPPED_DATE BETWEEN dateadd(m, datediff(m, 0, GetDate()), 0)
AND
dateadd(m, datediff(m, -1, GetDate()), 0)
GROUP BY
DBO.SHIPPER.PACKLIST_ID,
DBO.SHIPPER.CUST_ORDER_ID
ORDER BY
dbo.shipper.SHIPPED_DATE;
希望这对您有帮助。