【问题标题】:How to pivot multiple columns (int and date)?如何旋转多个列(int 和 date)?
【发布时间】:2022-01-07 11:45:49
【问题描述】:
CREATE TABLE dbo.children_bd (
    birthday_id int,
    child_birthday_id int,
    notification_parents date,
    notification_grandparents date,
    invitation_parents_id int,
    invitation_grandparents_id int
);

INSERT INTO dbo.children_bd
VALUES (1,9, '02-01-2021','07-01-2021', 4, 5);

这是我的代码:

select birthday_id, child_birthday_id, tm, rm
from (
    select p.birthday_id, p.child_birthday_id, p.notification_parents,
p.notification_grandparents, p.invitation_parents_id, p.invitation_grandparents_id
    from dbo.children_bd p
) t
UNPIVOT
(tm for id in (invitation_parents_id, invitation_grandparents_id)) pvt1
UNPIVOT
(rm for rid in (notification_parents, notification_grandparents)) pvt2

我收到这个:

+------------+-------------------+-----+-------------+
|birthday_id | child_birthday_id | tm  |  rm         |
+------------+------------------ +-----+-------------+
|  1         |        9          |  4  | 2021-02-01  |
|  1         |        9          |  4  | 2021-07-01  |
|  1         |        9          |  5  | 2021-02-01  |
|  1         |        9          |  5  | 2021-07-01  |
+-------+----------+-------------+-----+--------------

但我想收到这个:

+------------+-------------------+-----+-------------+
|birthday_id | child_birthday_id | tm  |  rm         |
+------------+------------------ +-----+-------------+
|  1         |        9          |  4  | 2021-02-01  |
|  1         |        9          |  5  | 2021-07-01  |
+-------+----------+-------------+-----+--------------

【问题讨论】:

标签: sql sql-server tsql pivot


【解决方案1】:

如果您想取消透视多个值,可以使用 CROSS APPLYtable value constructor

SELECT c.birthday_id,
       c.child_birthday_id,
       upvt.Type,
       upvt.NotificationDate,
       upvt.InvitationID
FROM   dbo.children_bd AS c
       CROSS APPLY 
       (VALUES 
           ('Parents', c.notification_parents, c.invitation_parents_id),
           ('Grandparents', c.notification_grandparents, c.invitation_grandparents_id)
        ) AS upvt (Type, NotificationDate, InvitationID);

Example on db<>fiddle

【讨论】:

  • 非常感谢!!!! )))))
  • @Aleksandra 你熟悉接受答案吗?
猜你喜欢
  • 1970-01-01
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-26
  • 2021-08-11
  • 2019-11-30
  • 1970-01-01
相关资源
最近更新 更多