您是否可以将我的问题视为重复,但我没有从其中任何一个获得答案,或者我无法创建查询。
我有一张如下表格。
---------------------------------------------------------------------------------
| Customer Name | Date | Product Name | Qty | Rate | Amount |
---------------------------------------------------------------------------------
| Customer1 | 10/10/2014 | Product1 | 10 | 100.00 | 1000.00 |
| Customer1 | 12/10/2014 | Product1 | 1 | 0.00 | 0.00 |
| Customer2 | 14/10/2014 | Product1 | 10 | 100.00 | 1000.00 |
| Customer1 | 16/10/2014 | Product1 | 10 | 100.00 | 1000.00 |
| Customer2 | 16/10/2014 | Product2 | 10 | 100.00 | 1000.00 |
| Customer2 | 16/10/2014 | Product2 | 1 | 0.00 | 0.00 |
| Customer1 | 20/10/2014 | Product2 | 20 | 150.00 | 1500.00 |
---------------------------------------------------------------------------------
我想显示如下结果......
---------------------------------------------------------
| Customer Name | Product Name | Qty | Free |
---------------------------------------------------------
| Customer1 | Product1 | 20 | 1 |
| Customer1 | Product2 | 20 | 0 |
| Customer2 | Product1 | 10 | 0 |
| Customer2 | Product2 | 10 | 1 |
---------------------------------------------------------
这意味着在日期范围内根据Qty
/ Rate
将Amount
列拆分为两个。
在我的程序中,我使用将免费数量保存为0.00
费率。
我已经看过并尝试了很多流程但却失败了。
我的SQL
查询如下所示。
SELECT CustomerName,ProductName,SUM(Qty), CASE WHEN Rate > 0 AND Amount > 0, CASE WHEN Rate < 1 AND Amount < 1 FROM salesdetails WHERE InvoiceDate BETWEEN '02/11/2014' AND '13/11/2014' GROUP BY ProductId, SoldTo ORDER BY CustomerName ASC
但它显示错误。
当我尝试......
SELECT CustomerName,ProductName,SUM(Qty) FROM salesdetails WHERE InvoiceDate BETWEEN '" & dtt & "' AND '" & dtf & "' AND Rate > 0 AND Amount > 0 GROUP BY ProductId, CustomerName ORDER BY CustomerName ASC
它显示单列(SUM(Qty)
)中的记录跳过免费数量(Rate = 0),因为我已经编写了查询来执行此操作。
查询应该是什么?
请帮我解决这个问题。
此致
答案 0 :(得分:2)
经过测试和工作:
SELECT Customer,
Product,
SUM(IF(Rate>0,Qty,0)) AS Qty,
SUM(IF(Rate=0,Qty,0)) AS Free
FROM salesdetails
WHERE InvoiceDate BETWEEN '02/10/2014' AND '13/11/2014'
GROUP BY Customer, Product;