SQL查询将表分组为表表?

问题描述

我正在将Power BI查询“转换”为SQL查询。关键查询之一执行以下操作:

  1. 获取下表:
+-----+-----+----------+
| PID | FID | Quantity |
+-----+-----+----------+
| 1   | A   | 15       |
+-----+-----+----------+
| 1   | B   | 2        |
+-----+-----+----------+
| 2   | B   | 3        |
+-----+-----+----------+
| 2   | D   | 8        |
+-----+-----+----------+
| 3   | C   | 2        |
+-----+-----+----------+
  1. 按PID分组,保留所有行(每个Data一个表):
+-----+-------+
| PID | Table |
+-----+-------+
| 1   | Data  |
+-----+-------+
| 2   | Data  |
+-----+-------+
| 3   | Data  |
+-----+-------+
  1. COUNT运行一些自定义逻辑/操作(其中一些非常复杂,因此不只是MAXData等),并翻转每个Data到每行一个新表中:
+-----+-------+-------------+
| PID | Table | Transformed |
+-----+-------+-------------+
| 1   | Data  | Data        |
+-----+-------+-------------+
| 2   | Data  | Data        |
+-----+-------+-------------+
| 3   | Data  | Data        |
+-----+-------+-------------+
  1. 展开Transformed列:
+-----+----------------+----------------+
| PID | ResultColumn-1 | ResultColumn-2 |
+-----+----------------+----------------+
| 1   | SomeResult-1   | SomeResult-1b  |
+-----+----------------+----------------+
| 2   | SomeResult-2   | SomeResult-2b  |
+-----+----------------+----------------+
| 3   | SomeResult-3   | SomeResult-3b  |
+-----+----------------+----------------+

可以在sql中执行此过程吗?我本以为我们可以将Group By与某些自定义功能一起使用,但并不完全确定该怎么做-任何指导将不胜感激。

谢谢!


样本输出

+-----+------------------+----------------+
| PID | ResultColumn-1   | ResultColumn-2 |
+-----+------------------+----------------+
| 1   | There are 2 of B | and 15 of A    |
+-----+------------------+----------------+
| 2   | There are 8 of D | and 3 of B     |
+-----+------------------+----------------+
| 3   | There are 2 of C |                |
+-----+------------------+----------------+

解决方法

您可以使用row_number()和条件聚合来做到这一点:

select 
    pid,max(case when rn = 1 then concat('There are ',quantity,' of ',fid) end) res1,max(case when rn = 2 then concat('And ',fid) end) res2
from (
    select 
        t.*,row_number() over(partition by pid order by fid desc) rn
    from mytable t
) t
group by pid

请注意,这假设每个pid最多有2行,如数据所示。否则,您可能需要使用更多条件表达式来扩展select子句。

,

是的,可以使用JOIN在它们之间加入,然后可以将结果分组或对其进行进一步处理。

您的初始查询将类似于:

SELECT 
    PID,Table,Transformed,ResultColumn-1,ResultColumn-2
FROM 
    table1 t1
LEFT JOIN table2 t2 ON t2.PID = t1.PID 
LEFT JOIN table3 t3 ON t3.PID = t1.PID 
LEFT JOIN table4 t4 ON t4.PID = t1.PID 

也就是说,PID是主键,在其他表中用作外键。

如果您提供了预期的结果,那么我们可以为您提供一个产生此结果的初始查询,您可以将其用作启动器!