将动态参数传递给交叉表子查询

时间:2017-03-21 14:13:49

标签: postgresql inner-join postgresql-9.4

我有那样的表:

 table:
 | id | key  | label  | amount |
 |----|------|--------|--------|
 | 1  | 1    | label1 | 10     |
 | 2  | 1    | label2 | 15     |
 | 3  | 1    | label3 | 99     |
 | 4  | 2    | label4 | 33     |
 | 5  | 2    | label2 | 10     |

fkey是其他表的外键。

我需要在交叉表中使用结果并为这些保留空值,其中没有关系:

select * from crosstab(
   'with labels (lbl) as ( ' ||
   '  values (''label2''), (''label3''), (''label4'') ' ||
   ') ' ||
   'select 1, l.lbl, t.amount ' || 
   'from labels l ' ||
   '  left outer join "table" t on l.lbl = t.label and t.key = 1 ' ||
   'order by l.lbl' ) AS (
fkey integer, label1 integer, label2 integer, label3 integer)

并且结果与我预期的一样(对于key = 1):

 |    | key  | label2 | label3 | label4 |
 |----|------|--------|--------|--------|
 | 1  | 2    | 15     | 99     | NULL   |

for key = 2

select * from crosstab(
   'with labels (lbl) as ( ' ||
   '  values (''label2''), (''label3''), (''label4'') ' ||
   ') ' ||
   'select 2, l.lbl, t.amount ' || 
   'from labels l ' ||
   '  left outer join "table" t on l.lbl = t.label and t.key = 2 ' ||
   'order by l.lbl' ) AS (
fkey integer, label1 integer, label2 integer, label3 integer)

结果是:

 |    | key  | label2 | label3 | label4 |
 |----|------|--------|--------|--------|
 | 1  | 2    | 10     | NULL   | 33     |

select 1, l.lbl, t.amount中的回拨键是硬编码的,因为如果没有关系,我需要保留查询键(因为t.key返回NULL)。

现在我需要将此查询用作db中每个键的子查询。所以我需要这样的东西:

with keys(key) as (
  values (1), (2), (3)
)
select * from keys
  left join (select * from crosstab(
    'with labels (lbl) as ( ' ||
    '  values (''label2''), (''label3''), (''label4'') ' ||
    ') ' ||
    'select ??, l.lbl, t.amount ' || 
    'from labels l ' ||
    '  left outer join "table" t on l.lbl = t.label and t.key = ?? ' ||
    'order by l.lbl' ) AS (
      key integer, label1 integer, label2 integer, label3 integer
    )
 ) I on (keys.key = I.key)

是否可以将密钥绑定到??标记的位置?

这是测试人员http://rextester.com/JMUBI41337(标记为2的标记仅在密钥为2时才有效。)

预期结果:

 |    | key  | label2 | label3 | label4 |
 |----|------|--------|--------|--------|
 | 1  | 1    | 15     | 99     | NULL   |
 | 2  | 2    | 10     | NULL   | 33     |
 | 3  | 3    | NULL   | NULL   | NULL   |

解决。链接到Clodoaldo Neto的工作解决方案:http://rextester.com/SYWQ20694

1 个答案:

答案 0 :(得分:1)

"data": [ { "date": "2017-03-21T10:25:47.848959Z", "version": "1.12", "changes": [ { "tool": "General", "date": "2017-03-21T10:26:22.838785Z", "type": "Fix", "title": "dfa", "description": "" }, { "tool": "General", "date": "2017-03-21T10:26:08.379112Z", "type": "Fix", "title": "dasf", "description": "" } ] }, { "date": "2017-03-21T10:33:43Z", "version": "1.01.12", "changes": [ { "tool": "General", "date": "2017-03-21T10:44:35.143232Z", "type": "Improvement", "title": "qw", "description": "" }, { "tool": "Costs", "date": "2017-03-21T10:34:12.482258Z", "type": "Fix", "title": "dfaasss", "description": "" } ] } ] lateral

format