首页 > 解决方案 > 如何编写此 SQL 代码并在同一张表上输出?

问题描述

我知道在 SQL Server 中有一种方法可以做到这一点,但是经过数小时的故障排除后,我仍然没有弄清楚。

我想要同一张表中的性别和 2 年生存输出。这是我用于按性别分开输出的代码:

-- Count # of patients by gender and count the number of patients that are alive - Females

SELECT twoYrSurv AS WOMEN_2_YR_SURVIVAL, COUNT('gender') AS GENDER_TOTALS
FROM dataLungCancer1$
WHERE gender = 'Female'
GROUP BY twoYrSurv

-- Count # of patients by gender and count the number of patients that are alive - Males

SELECT twoYrSurv AS MEN_2_YR_SURVIVAL, COUNT('gender') AS GENDER_TOTALS
FROM dataLungCancer1$
WHERE gender = 'Male'
GROUP BY twoYrSurv

-- Results after changing group by clause
SELECT twoYrSurv AS Two_YR_SURVIVAL, COUNT('gender') AS GENDER_TOTALS
FROM dataLungCancer1$
GROUP BY gender, twoYrSurv

输出

Two_YR_SURVIVAL GENDER_TOTALS
-----------------------------
Alive              86
Alive              201
Deceased           60
Deceased           103

标签: sql-servertsql

解决方案


解决方案:

SELECT twoYrSurv AS TWO_YR_SURVIVAL, gender AS GENDER, COUNT('gender') AS GENDER_TOTALS
FROM dataLungCancer1$
GROUP BY gender, twoYrSurv

结果:

Lung_Cancer_Survival_By_Gender


推荐阅读