【问题标题】:SQL query lists belonging to main table as columns on main table属于主表的 SQL 查询列表作为主表上的列
【发布时间】:2021-12-10 23:08:47
【问题描述】:

我有一个基于此主题中提出的问题的后续问题: SQL query subtable in columns from main query

我已经设法得到下表,上面的主题中回答了查询:

uuid code title-en title-de
111-etc 123 english 123 deutch 123
222-etc 321 english 321 deutch 321

在我已经拥有的结果旁边,我想扩展 SQL 以基于另一个表向结果添加额外的(动态)列。

Table_1 和 table_1_lang (当然)是一样的:

table_1

uuid code
111-etc 123
222-etc 321

table_1_lang

uuid lang_code title
111-etc en english 123
111-etc de deutch 123
222-etc en english 321
222-etc de deutch 321

table_2(包含 0-n 个列表的动态列表)

uuid list_code value order
111-etc list_code_1 100 0
111-etc list_code_2 50 1
222-etc list_code_1 200 2
222-etc list_code_2 30 0
222-etc list_code_3 10 1

我想要创建的结果(在上述结果旁边以及上一个主题中非常有用的答案)如下: 结果中列名中的“0”、“1”等是列表中的顺序字段。

结果:

uuid code title-en title-de condition-0-list_code condition-0-value condition-1-list_code condition-1-value condition-2-list_code condition-2-value
111-etc 123 english 123 deutch 123 list_code_1 100 list_code_2 50
222-etc 321 english 321 deutch 321 list_code_2 30 list_code_3 10 list_code_1 200

我正在非常努力地根据我已经收到的查询获得结果,并认为这只是之前查询的“扩展”,但我的 SQL 知识不是很好。

总结一下我到底需要什么: 使用上述表格:

  • table_1
  • table_1_lang
  • table_2(table_1 中的每个键/uuid 可以包含 0-n 行)

我想创建一个在“结果”中给出的集合。

“条件”的列名必须根据值“顺序”和要在结果列中显示的列(list_code 和值)动态创建。

所以 uuid '111-etc' 在 table_2 中有 2 个条目,您将在结果表的第 1 行中看到这些值。

'condition-2-list_code' 和 'condition-2-value' 在 uuid '111-etc' 的结果中为空,因为它们不在 table_2 中。对于 uuid '222-etc',这些值会填入结果表中。

谁能帮帮我?非常感谢您提前提供的帮助,非常感谢。

【问题讨论】:

  • 请澄清您的具体问题或提供更多详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: sql sql-server sql-server-2012


【解决方案1】:

您可以在 CROSS APPLY 内旋转。

对于两列数据透视,使用条件聚合通常更容易MAX(CASE WHEN

select
  t.uuid,
  t.code,
  [title-en] = len.title,
  [title-de] = lde.title,
  cond.*
from table_1 t
left join table_1_lang len on t.uuid = len.uuid and len.lang_code = 'en'
left join table_1_lang lde on t.uuid = lde.uuid and lde.lang_code = 'de'
CROSS APPLY (
    SELECT
      [condition-0-list_code] = MAX(CASE WHEN c.[order] = 0 THEN c.list_code END),
      [condition-0-value]     = MAX(CASE WHEN c.[order] = 0 THEN c.value END),
      [condition-1-list_code] = MAX(CASE WHEN c.[order] = 1 THEN c.list_code END),
      [condition-1-value]     = MAX(CASE WHEN c.[order] = 1 THEN c.value END),
      [condition-2-list_code] = MAX(CASE WHEN c.[order] = 2 THEN c.list_code END),
      [condition-2-value]     = MAX(CASE WHEN c.[order] = 3 THEN c.value END)
    FROM table_2 c
    WHERE c.uuid = t.uuid
) cond;

您也可以为table_1_lang 执行此操作

【讨论】:

  • 这种方式不是基于每个条件的 1-n 值动态的,但我也不知道“交叉应用”。所以这个答案对我有很大帮助,我会接受这个答案作为我的问题的解决方案。非常感谢!
  • 如果没有必要,最好不要做动态列。只需添加您认为需要的最大值即可,额外的将是null
猜你喜欢
  • 2021-12-08
  • 2016-11-07
  • 2019-11-12
  • 1970-01-01
  • 2012-09-04
  • 2016-12-25
  • 1970-01-01
  • 1970-01-01
  • 2020-05-05
相关资源
最近更新 更多