如何将下面的表中的两行组合起来,以便在下面看到结果表?
ID NAME GROUP OWNER
1 Shoes Bulls NULL
1 Shoes NULL Michael Jordan
2 Hat NULL NULL
2 Hat NULL Kobe Bryant
3 Boots NULL NULL
3 Boots NULL NULL
结果
ID NAME GROUP OWNER
1 Shoes Bulls Michael Jordan
2 Hat NULL Kobe Bryant
3 Boots NULL NULL
答案 0 :(得分:1)
SELECT ID, NAME, MAX(GROUP) AS GROUP, MAX(OWNER) AS OWNER
FROM YourTable
GROUP BY ID, NAME
答案 1 :(得分:0)
使用GROUP BY
和MAX
:
SELECT
ID,
MAX(NAME) AS NAME,
MAX(`GROUP`) AS `GROUP`,
MAX(OWNER) AS OWNER
FROM yourtable
GROUP BY ID
答案 2 :(得分:0)
对于显示的示例数据,这将起作用。
SELECT ID, NAME, MAX(GROUP) AS GROUP, MAX(OWNER) AS OWNER
FROM YourTable
GROUP BY ID, NAME
答案 3 :(得分:0)
首先修复基表,以便通过缺少行(而不是null)对缺失的信息进行建模,提供一些查看的表以提供缺失数据的默认叙述,然后显示结果:
(标准SQL-99语法,在SQL Server 2008 R2上测试)
WITH Apparel -- base table
AS
(
SELECT *
FROM (
VALUES (1, 'Shoes'),
(2, 'Hat'),
(3, 'Test')
) AS T (apparel_ID, apparel_name)
),
ApparelGroups -- base table
AS
(
SELECT *
FROM (
VALUES (1, 'Bulls')
) AS T (apparel_ID, apparel_group_name)
),
ApparelOwners -- base table
AS
(
SELECT *
FROM (
VALUES (1, 'Michael Jordan'),
(2, 'Kobe Bryant')
) AS T (apparel_ID, apparel_owner_name)
),
ApparelGroupsNarratives -- viewed table
AS
(
SELECT apparel_ID, apparel_group_name AS apparel_group_narrative
FROM ApparelGroups
UNION
SELECT apparel_ID, '(no group)' AS apparel_group_narrative
FROM Apparel
WHERE apparel_ID NOT IN (SELECT apparel_ID FROM ApparelGroups)
),
ApparelOwnersNarratives -- viewed table
AS
(
SELECT apparel_ID, apparel_owner_name AS apparel_owner_narrative
FROM ApparelOwners
UNION
SELECT apparel_ID, '(no owner)' AS apparel_owner_narrative
FROM Apparel
WHERE apparel_ID NOT IN (SELECT apparel_ID FROM ApparelOwners)
)
SELECT a.apparel_ID, a.apparel_name,
g.apparel_group_narrative, n.apparel_owner_narrative
FROM Apparel a
INNER JOIN ApparelGroupsNarratives g
ON a.apparel_ID = g.apparel_ID
INNER JOIN ApparelOwnersNarratives n
ON a.apparel_ID = n.apparel_ID;