创建SQL查询引用了几个表

时间:2017-11-21 23:41:01

标签: sql sql-server database

我试图用自己的观点来做这件事,但遗憾的是我没有所需的技能或知识。

我已经提供了一些虚拟数据来演示。

uri当然= object_uri

TABLE_RECORD

+-----+---------------+---------+
| uri |     title     | client  |
+-----+---------------+---------+
|   1 | australia     | peter   |
|   2 | new zealand   | peter   |
|   3 | canada        | chris   |
|   4 | united states | mitch   |
|   5 | ireland       | michael |
|   6 | scotland      | mitch   |
+-----+---------------+---------+

TABLE_UDF

+------------+--------------+----------------+
| object_uri | udf_type_uri | udf_type_value |
+------------+--------------+----------------+
|          1 |         2005 | 1/12/2007      |
|          2 |         2005 | 2/04/2008      |
|          2 |         2006 | 3/04/2009      |
|          3 |         2005 | 4/05/2010      |
|          4 |         2006 | 12/04/2016     |
|          5 |         2005 | 14/05/2005     |
|          5 |         2006 | 14/05/2006     |
|          6 |         2005 | 20/01/2017     |
+------------+--------------+----------------+

预期输出

+-----+---------------+---------+------------+------------+
| uri |     title     | client  | udf_type_1 | udf_type_2 |
+-----+---------------+---------+------------+------------+
|   1 | australia     | peter   | 1/12/2007  |            |
|   2 | new zealand   | peter   | 2/04/2008  | 3/04/2009  |
|   3 | canada        | chris   | 4/05/2010  |            |
|   4 | united states | mitch   |            | 12/04/2016 |
|   5 | ireland       | michael | 14/05/2005 | 14/05/2006 |
|   6 | scotland      | mitch   | 20/01/2017 |            |
+-----+---------------+---------+------------+------------+

非常感谢高级版。

2 个答案:

答案 0 :(得分:1)

如果我理解正确,这是带有条件聚合的join

select r.uri, r.title, r.client,
       max(case when u.udf_type_uri = 2005 then udf_type_value end) as udf_type_1,
       max(case when u.udf_type_uri = 2006 then udf_type_value end) as udf_type_2
from record r join
     udf u
     on r.uri = u.object_uri
group by r.uri, r.title, r.client;

答案 1 :(得分:0)

SELECT
    *
FROM
    table_record
LEFT JOIN
(
    SELECT
        object_uri,
        MAX(CASE WHEN udf_type_uri = 2005 THEN udf_type_value END)   AS udf_type_1,
        MAX(CASE WHEN udf_type_uri = 2006 THEN udf_type_value END)   AS udf_type_2
    FROM
        table_udf
    GROUP BY
        object_uri
)
    table_udf
        ON  table_udf.object_uri = table_record.uri

内部查询将udf表格压缩为每uri行一行,并使用MAX()CASE确保将正确的udf放置在正确的列中。然后你就像平常一样加入表格。

(也可以使用PIVOT完成,但这对我来说似乎总是笨拙......) https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx