按增值税率排列搜索结果

时间:2017-08-16 12:46:51

标签: php mysql

我有一个名为invoiceItems的表。它包含发票的各行。它包含以下字段:

  • invoiceItemId(主键)
  • invoiceId(表格发票的主键)
  • productId(表产品的主键)
  • 数量
  • vatRate(0%,6%,12%,21%)

我想查询数据库并选择具有特定发票编号的所有invoiceItems。然后我想回显一下该发票中出现的不同vatRates,以及每个vatRate的增值税总额。

例如,如果结果是:

  • invoiceItemId:1,invoiceId:17,productId:23,Rate:10(€),Quantity:10,vatRate:6%
  • invoiceItemId:2,invoiceId:17,productId:7,Rate:100(€),Quantity:1,vatRate:21%
  • invoiceItemId:3,invoiceId:17,productId:8,Rate:10(€),Quantity:5,vatRate:12%

我想回应一下:

发票号码17

增值税6%:6欧元 增值税12%:6欧元 增值税21%:21欧元

$sql = "SELECT * FROM invoiceItems WHERE invoiceId = ’17’”;
$query = $connect->query($sql);
$result = $query->fetch_assoc();

我知道我应该循环查看结果,但我有点卡住......

2 个答案:

答案 0 :(得分:1)

使用SQL中的GROUP BYSUM运算符构建。

    $sql = "SELECT vatRate, SUM(quantity * price * vatRate) as total FROM invoiceItems WHERE invoiceId = ’17’ GROUP BY vatRate”;
    $query = $connect->query($sql);

    while($result = $query->fetch_assoc()) { // Fetch for each vatrate
        // do what you want to do with the vats
        // use $result["vatRate"] and $result["total"]
    } 

答案 1 :(得分:0)

您正在寻找http://php.net/manual/en/control-structures.while.php

的while循环

然后你可以

public static void main(String[] args) throws IOException {
    FileInputStream fis = new FileInputStream("in.txt");
    BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

    FileOutputStream fosA = new FileOutputStream("out_A.txt");
    FileOutputStream fos1 = new FileOutputStream("out_1.txt");
    FileOutputStream fos = null;

    System.out.println("Reading File line by line using BufferedReader");

    String line = reader.readLine();
    while (line != null) {
        System.out.println(line);
        if(line.equals("A"))
        {
            fos = fosA;
            line = reader.readLine();
            continue;
        }

        if(line.equals("1"))
        {
            fos = fos1;
            line = reader.readLine();
            continue;
        }

        fos.write(line.getBytes());
        fos.write('\n');
        fos.flush();
        line = reader.readLine();
    }

    fos.close();
    fosA.close();
    fos1.close();
}

查看文档http://php.net/manual/en/mysqli-result.fetch-assoc.php

中的示例