从sql中的2个不同表中求和两个计数

时间:2017-08-22 03:09:25

标签: sql database oracle

我在db上有两个表:

xhrFields: {
    withCredentials: true
},

我想显示这个视图:

1. memberOne

memberName | gender
===================
Jack       | M
Steve      | M
Audrey     | F


2. memberTwo

memberName | gender
===================
Sarah      | F
Steve      | M
Audrey     | F
Alvin      | M

我执行了这段代码

Gender         | Total
=======================
M              | 4
F              | 3

这就是我得到的:

SELECT t.Gender, COUNT(t.Gender) Total FROM memberOne t
GROUP BY t.Gender
UNION ALL
SELECT d.Gender, COUNT(d.Gender) Total FROM memberTwo d
GROUP BY d.Gender
;

如何从每张表中总结M和F的总和?我应该用条件检查性别吗? 任何帮助将不胜感激,谢谢。

5 个答案:

答案 0 :(得分:1)

将您的上一个查询包含在另一个查询中,该查询将M和F的数量相加。

SELECT
    G, SUM(Total) 
FROM
    (SELECT  
         t.Gender G, COUNT(t.Gender) Total 
     FROM
         memberOne t
     GROUP BY 
         t.Gender

    UNION ALL

    SELECT 
        d.Gender G, COUNT(d.Gender) Total 
    FROM 
        memberTwo d
    GROUP BY 
        d.Gender) 
GROUP BY 
    gender

答案 1 :(得分:1)

这里的一种方法是将两个表格中的性别联合在一起,然后进行单一聚合以获得男性和女性的数量。

func prepareNotification() {

    let content = UNMutableNotificationContent()
    content.title = "Eva Reminder"
    content.body = "2 Days Left Before Your Period Days."
    content.sound = UNNotificationSound.default()

    var components = DateComponents()
    components.day = numberOfDaySelected - 2
    components.hour = 7
    components.minute = 0
    let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
    let request = UNNotificationRequest(identifier: "eva.notification", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

在这里演示:

Rextester

答案 2 :(得分:1)

您需要使用UNION ALL,然后应用COUNT

SELECT
    gender as Gender,
    COUNT(*) as Total
FROM
(
    SELECT gender
    FROM memberOne
    UNION ALL
    SELECT gender
    FROM memberTwo
) group by gender

答案 3 :(得分:0)

SELECT n.Gender, COUNT(n.Gender) Total FROM
(
SELECT t.Gender, COUNT(t.Gender) Total FROM memberOne t
GROUP BY t.Gender
UNION ALL
SELECT d.Gender, COUNT(d.Gender) Total FROM memberTwo d
GROUP BY d.Gender
) n
GROUP BY n.Gender

在最后一次查询后重复select和group by

答案 4 :(得分:0)

完成初始查询目标的一种方法是:

选择性别,总和(总计)总计 从(您现有的查询)q q.Gender分组

另一种方式是:

选择性别,计数(性别)总计 从 (从membeOne中选择性别   全联盟   从memberTwo中选择性别)q q.Gender分组