使用多个联接时,是否可以将某一特定列的行透视成一行,而不是透视成列?

时间:2019-04-10 17:04:16

标签: sql-server

我无法将行透视成一列的一行,也无法设置别名列名

我尝试编写联接,然后将其放入选择中,然后旋转该数据集。

select * from (
select DET.*, DETF.ExtractTemplateId, DetF.FieldId, DEF.Field from DataExtractTemplate DET
    join DataExtractTemplateFields DETF
    on DET.Id = DETF.ExtractTemplateId
    join DataExtractFields DEF 
on DETF.FieldId = DEF.Id
    WHERE ClientId = 1) AS Src
PIVOT (
sum(Id)
for FieldId in ([1],[2],[6],[7])
) Pvt

我得到这个:

Field           1        2       6      7
____________________________________________
First Name      1       NULL    NULL    NULL
Last Name       NULL    1       NULL    NULL
NPI             NULL    NULL    1       NULL
Phone Number    NULL    NULL    NULL    1

但是我想要这个

Field1       Field2     Field6  Field7
____________________________________
First Name   Last Name   NPI    Phone Number    

Screenshot of ERD

2 个答案:

答案 0 :(得分:1)

要理解您要执行的操作并不容易,但是使用交叉表查询似乎可以为您提供帮助。

SELECT SomeGroupingColumns, 
    MAX(CASE WHEN DetF.FieldId = 1 THEN DEF.Field END) AS Field1, 
    MAX(CASE WHEN DetF.FieldId = 2 THEN DEF.Field END) AS Field2, 
    MAX(CASE WHEN DetF.FieldId = 6 THEN DEF.Field END) AS Field6, 
    MAX(CASE WHEN DetF.FieldId = 7 THEN DEF.Field END) AS Field7
FROM DataExtractTemplate DET
JOIN DataExtractTemplateFields DETF ON DET.Id = DETF.ExtractTemplateId
JOIN DataExtractFields         DEF  ON DETF.FieldId = DEF.Id
WHERE ClientId = 1
GROUP BY SomeGroupingColumns;

答案 1 :(得分:0)

此代码有效!但是,使用我更新的代码,我得到的是空值

function addPayment($data) {
    global $db;
    if (is_array($data)) {
        $stmt = $db->prepare('INSERT INTO `payments` (txnid, payment_amount, payment_status, itemid, createdtime) VALUES(?, ?, ?, ?, ?)');
        $stmt->bind_param(
            'sdsss',
            $data['txn_id'],
            $data['payment_amount'],
            $data['payment_status'],
            $data['item_number'],
            date('Y-m-d H:i:s')
        );
        $stmt->execute();
        $stmt->close();
        return $db->insert_id;
    }
    return false;
}

Row showing nulls