【发布时间】:2017-08-17 12:07:22
【问题描述】:
给定一个 SQL 查询如下
DECLARE @StartDate NVARCHAR(MAX) = '20170815'
DECLARE @FinishDate NVARCHAR(MAX) = '20170815'
SELECT
cid.ItemCode,
cid.InvoiceCode,
SUM(ROUND(cid.ExtPrice, 2)) AS 'TotalExGST'
FROM CustomerInvoice ci
JOIN CustomerInvoiceDetail cid
ON ci.InvoiceCode = cid.InvoiceCode
WHERE ci.IsVoided = 0
AND dbo.ConvertDate_C(ci.InvoiceDate)
BETWEEN @StartDate AND @FinishDate
GROUP BY ci.invoicecode, ItemCode
UNION ALL
SELECT
'Freight',
ci.InvoiceCode,
ci.Freight
FROM CustomerInvoice ci
WHERE ci.IsVoided = 0
AND dbo.ConvertDate_C(ci.InvoiceDate) BETWEEN @StartDate AND @FinishDate
GROUP BY ci.invoicecode, ci.Freight
返回这样的数据(为简单起见,仅显示一张发票)
╔═════════════╦══════════════╦══════════════╗
║ Item Code ║ Invoice Code ║ Total Ex GST ║
╠═════════════╬══════════════╬══════════════╣
║ Freight ║ INV-255390 ║ 20.000000 ║
╠═════════════╬══════════════╬══════════════╣
║ ITEM-002605 ║ INV-255390 ║ 47.120000 ║
╠═════════════╬══════════════╬══════════════╣
║ ITEM-002679 ║ INV-255390 ║ 11.260000 ║
╠═════════════╬══════════════╬══════════════╣
║ ITEM-002687 ║ INV-255390 ║ 10.860000 ║
╠═════════════╬══════════════╬══════════════╣
║ ITEM-028905 ║ INV-255390 ║ 58.480000 ║
╚═════════════╩══════════════╩══════════════╝
我如何获得每张发票上的行项目总数,并将运费金额除以该总数,然后将其与项目价格相加?
项目和价格在CustomerInvoiceDetail 表上,而运费在CustomerInvoice 表上,这些可以在InvoiceCode 列上连接。
预期输出如下所示,计算如下:
Number of items on invoice = 4
Freight cost = 20
Split Freight Cost = 20 / 4 = 5
Then add 5 to all the items, and thus remove freight row from the query.
╔═════════════╦═════════════╦════════════╗
║ ItemCode ║ InvoiceCode ║ TotalExGST ║
╠═════════════╬═════════════╬════════════╣
║ ITEM-002605 ║ INV-255390 ║ 52.12 ║
╠═════════════╬═════════════╬════════════╣
║ ITEM-002679 ║ INV-255390 ║ 16.26 ║
╠═════════════╬═════════════╬════════════╣
║ ITEM-002687 ║ INV-255390 ║ 15.86 ║
╠═════════════╬═════════════╬════════════╣
║ ITEM-028905 ║ INV-255390 ║ 63.48 ║
╚═════════════╩═════════════╩════════════╝
【问题讨论】:
-
预期的输出是什么样子的
-
查看更新的问题 ;)
标签: sql sql-server sql-server-2008-r2