SQL查询 - 将结果行放入列中

时间:2018-02-01 21:21:25

标签: sql sql-server pivot pivot-table

长话短说,我想从图片的顶部拍摄结果,让它们显示为底部。 TestName字段有1300多个选项,所以我猜测一个子查询来拉TestName,然后根据它创建一个列是最好的。这适用于Microsoft SQL数据库。

Orginal Table:
+-----------------+--------------+------------------+
| AccessionNumber |   TestName   |      Result      |
+-----------------+--------------+------------------+
| K09035053       | Organism     | Rhodococcus equi |
| K09035053       | Timentin     | Susceptible      |
| K09035053       | Erythromycin | Susceptible      |
| K09035053       | Sulfa-Drugs  | Resistant        |
+-----------------+--------------+------------------+

Fixed Table:
+-----------------+------------------+-------------+--------------+-------------+
| AccessionNumber |     Organism     |  Timentin   | Erythromycin | Sulfa-Drugs |
+-----------------+------------------+-------------+--------------+-------------+
| K09035053       | Rhodococcus equi | Susceptible | Susceptible  | Resistant   |
+-----------------+------------------+-------------+--------------+-------------+

1 个答案:

答案 0 :(得分:1)

对于MSQL,以下内容应该有效。

<?php
class Validator 
{
    public $data;

    public $fields = [
        'name'    => [
            'name'  => 'name',
            'error' => 'Name is empty.'
        ],
        'address'    => [
            'name'  => 'address',
            'error' => 'Name is empty.'
        ],
        'zipcode'    => [
            'name'  => 'zipcode',
            'error' => 'Name is empty.'
        ],
        'place'    => [
            'name'  => 'place',
            'error' => 'Name is empty.'
        ],
        'phone'    => [
            'name'  => 'phone',
            'error' => 'Name is empty.'
        ],
        'email'    => [
            'name'  => 'email',
            'error' => 'Name is empty.'
        ],
        'subject'    => [
            'name'  => 'subject',
            'error' => 'Name is empty.'
        ],
        'message'    => [
            'name'  => 'message',
            'error' => 'Name is empty.'
        ]
    ];

    public $errors = [];

    public function __construct($data){
        $this->data = $data;

        return $this->validate($this->data);

    }

    public function validate(){

        foreach($this->fields as $key => $value){
            $this->validate_field($this->fields[$key]);
        }

        if (count($this->errors) == 0) {
            return 'Formulier succesvol ingevuld, wordt verzonden';
        } else {
            return $this->errors;
        }
    }

    public function validate_field($value){
        if (empty($this->data[key($value)])) {
            $this->errors[$value['name']] = $value['error'];
            return;
        }

        $this->data[$value['name']] = htmlspecialchars(trim($value['name']));
    }
}

编辑:

请注意,您的TestName有很多选项,因此您可能仍希望使用PIVOT,但在T-SQL中动态生成SQL字符串,然后执行该字符串。