SQL GROUP BY列值

时间:2018-12-13 16:42:28

标签: sql group-by ssms

当选择下面的数据时,我想进行设置,以便我可以按列分组,以便所有都为“ Y”。下图显示了当前的外观;

enter image description here

enter image description here

第二张图片显示了最终结果的外观。

SELECT p.FirstName
    ,p.Surname
    ,CASE
        WHEN a.ActivityName = 'Jumping' THEN 'Y'
        ELSE 'N'
    END AS 'Jumping'
    ,CASE
        WHEN a.ActivityName = 'Dancing' THEN 'Y'
        ELSE 'N'
    END AS 'Dancing'
    ,CASE
        WHEN a.ActivityName = 'Walking' THEN 'Y'
        ELSE 'N'
    END AS 'Walking'
FROM #TempActivity a 
    INNER JOIN #TempPerson p ON a.AID = p.ActivityID
WHERE FirstName = 'John'
    AND Surname = 'Smith'

下面,我复制了整个表创建过程,以便您可以查看所有数据和表结构。我发布了在这种情况下设计表的一种更好的方法,但这只是一个示例,所以我知道在其他地方应用的方法;

CREATE TABLE #TempActivity(
AID INT
,ActivityName VARCHAR(100)
)

CREATE TABLE #TempPerson(
PID INT
,FirstName VARCHAR(100)
,Surname VARCHAR(100)
,ActivityID INT
)

INSERT INTO #TempActivity
VALUES (1,'Jumping')
    ,(2,'Dancing')
    ,(3,'Walking')

INSERT INTO #TempPerson
VALUES (1,'John', 'Smith', 1)
    ,(2,'John', 'Smith', 2)
    ,(3,'John', 'Smith', 3)
    ,(4,'Jane','Smith', 1)
    ,(5,'Jane','Smith', 2)

SELECT * FROM #TempActivity
SELECT * FROM #TempPerson

SELECT p.FirstName
    ,p.Surname
    ,a.ActivityName
  FROM #TempActivity a 
INNER JOIN #TempPerson p ON a.AID = p.ActivityID
  WHERE FirstName = 'John'
AND Surname = 'Smith'

SELECT p.FirstName
    ,p.Surname
    ,CASE
        WHEN a.ActivityName = 'Jumping' THEN 'Y'
        ELSE 'N'
    END AS 'Jumping'
    ,CASE
        WHEN a.ActivityName = 'Dancing' THEN 'Y'
        ELSE 'N'
    END AS 'Dancing'
    ,CASE
        WHEN a.ActivityName = 'Walking' THEN 'Y'
        ELSE 'N'
    END AS 'Walking'
    FROM #TempActivity a 
INNER JOIN #TempPerson p ON a.AID = p.ActivityID
WHERE FirstName = 'John'
AND Surname = 'Smith'

DROP TABLE #TempActivity;
DROP TABLE #TempPerson;

2 个答案:

答案 0 :(得分:1)

SELECT p.FirstName
    ,p.Surname
    ,CASE WHEN SUM(CASE
        WHEN a.ActivityName = 'Jumping' THEN 1
        ELSE 0 END) > 0 THEN 'Y' 
        ELSE 'N' 
    END AS 'Jumping'
    ,CASE WHEN SUM(CASE
        WHEN a.ActivityName = 'Dancing' THEN 1
        ELSE 0 END) > 0 THEN 'Y' 
        ELSE 'N'
    END AS 'Dancing'
    ,CASE WHEN SUM(CASE
        WHEN a.ActivityName = 'Walking' THEN 1
        ELSE 0 END) > 0 THEN 'Y' 
        ELSE 'N'
    END AS 'Walking'
FROM #TempActivity a 
    INNER JOIN #TempPerson p ON a.AID = p.ActivityID
WHERE FirstName = 'John'
    AND Surname = 'Smith'
GROUP BY FirstName, SurName

答案 1 :(得分:0)

您可以只使用max()

select firstname, surname, max(jumping) as jumping,
       max(dancing) as dancing, max(walking) as walking
from #TempActivity a join
     #TempPerson p 
     on a.AID = p.ActivityID
where FirstName = 'John' and Surname = 'Smith'
group by firstname, surname;