我有以下表格结构,并试图从这些表格中做出报告:
___ BillableDatas
|--------|------------|---------|--------------|------------|
| BIL_Id | BIL_Date |BIL_Rate | BIL_Quantity | BIL_Status |
|--------|------------|---------|--------------|------------|
| 1 | 2018-03-01 | 105 | 2 | notcharged |
| 2 | 2018-03-01 | 30 | 2 | notcharged |
| 3 | 2018-03-02 | 115 | 2 | charged |
| 4 | 2018-03-03 | 105 | 1 | notcharged |
| 5 | 2018-03-04 | 105 | 1 | notcharged |
| 6 | 2018-03-05 | 105 | 3 | notcharged |
|--------|------------|---------|--------------|------------|
___ SalesTaxes
|--------|--------------|------------|
| STX_Id | STX_TaxeName | STX_Amount |
|--------|--------------|------------|
| 8 | Tax 1 | 5.000 |
| 9 | Tax 2 | 15.000 |
|--------|--------------|------------|
STX_Amount是一个百分比。
___ ApplicableTaxes
|-----------|-----------|
| ATX_BILId | ATX_STXId |
|-----------|-----------|
| 1 | 8 |
| 1 | 9 |
| 2 | 9 |
| 3 | 9 |
| 4 | 9 |
| 5 | 9 |
|-----------|-----------|
请注意,对于2018-03-05
,没有关税。
这样的方法就是这样:
|------------|--------------|------------|------------|-----------|
| BIL_Date | STX_TaxeName | BIL_Rate | STX_Amount | STX_Total |
|------------|--------------|------------|------------|-----------|
| 2018-03-01 | Tax 1 | 210.00 | 5.000 | 10.50 |
| 2018-03-01 | Tax 2 | 270.00 | 15.000 | 40.50 |
| 2018-03-03 | Tax 2 | 105.00 | 15.000 | 15.75 |
| 2018-03-04 | Tax 2 | 105.00 | 15.000 | 15.75 |
|------------|--------------|------------|------------|-----------|
我不希望具有状态的项目:收费
对总数的说明:
STX_TaxeName
是来自___ SalesTaxes的相关税的名称。BIL_Rate
是来自___ BillableDatas的BIL_Rate * BIL_Quantity
。STX_Amount
是___ SalesTaxes的税率。STX_Total
是BIL_Rate
的计算百分比。 (BIL_Rate*STX_Amount/100
)。我的最后一次尝试就是这个:
SELECT BIL_Date, STX_TaxeName, BIL_Rate * BIL_Quantity AS NewRate, STX_Amount
, BIL_Rate * BIL_Quantity * STX_Amount / 100 AS Total
FROM ___BillableDatas b
JOIN ___ApplicableTaxes bt ON bt.ATX_BILId = b.BIL_Id
JOIN ___SalesTaxes t ON t.STX_Id = bt.ATX_STXId
WHERE BIL_Status != 'charged'
ORDER BY BIL_Date, STX_TaxeName
如果需要,请参阅此SQLFiddle以帮助您:
http://sqlfiddle.com/#!9/41166/17
这个实际查询存在的问题是,它不会计算第2项,我也不知道为什么。
(2, '2018-03-01', '30.00', 2, 'notcharged')
感谢。
答案 0 :(得分:0)
我认为您只需要使用分组和聚合函数来获得所需的结果:
SELECT BIL_Date, STX_TaxeName, SUM(BIL_Rate * BIL_Quantity) AS NewRate, STX_Amount
, SUM(BIL_Rate * BIL_Quantity * STX_Amount / 100) AS Total
FROM ___BillableDatas b
JOIN ___ApplicableTaxes bt ON bt.ATX_BILId = b.BIL_Id
JOIN ___SalesTaxes t ON t.STX_Id = bt.ATX_STXId
WHERE BIL_Status != 'charged'
GROUP BY BIL_Date, STX_TaxeName
输出:
BIL_Date STX_TaxeName NewRate STX_Amount Total
2018-03-01 Tax 1 210 5 10.5
2018-03-01 Tax 2 270 15 40.5
2018-03-03 Tax 2 105 15 15.75
2018-03-04 Tax 2 105 15 15.75