如何获取多列中每个不同值的计数并将结果放在单独的列中?

时间:2015-05-24 12:21:18

标签: sql-server sqlite

我需要查询下表才能得到表格下方的结果。

表:

----------------------------------
| Name  |  Age   |  slot         |
|-------|--------|---------------|
|A      |20      | 1             |
|B      |30      | 2             |  
|C      |30      | 1             |                
|D      |20      | 1             |                
|E      |40      | 2             |                
|F      |40      | 3             |
|G      |50      | 3             |
----------------------------------

结果:

-------------------------------------------
|Age   |Age_Count     |Slot    |Slot_Count|
-------------------------------------------
|20    | 2            |1       |3         |
-------------------------------------------
|30    | 2            |2       |2         |
-------------------------------------------
|40    | 2            |3       |2         |
-------------------------------------------
|50    | 1            |
-----------------------

在搜索stackoverflow时,我发现了this question for single column个问题,并且[多个列的此链接](get the count of each distinct value in "Multiple" columns)问题。来自第二个链接的答案(对于多个库存的不同计数)显示在一个列下,我的要求与我在那里发布的答案完全不同。

提前致谢

1 个答案:

答案 0 :(得分:0)

您的要求有点奇怪。你确定要的吗?

如果是这样,这可能会有所帮助:

SET @x:=0,@y:=0,@m:=0,@n:=0;
SELECT 
    DISTINCT age,age_count, slot,slot_count 
FROM (
    SELECT 
        age, age_count, slot, slot_count
    FROM (
        SELECT 
            @x:=@x + 1 AS aid, age, COUNT(*) age_count
        FROM
            slots
        GROUP BY age
    ) a
    LEFT JOIN (
        SELECT 
            @y:=@y + 1 AS sid, slot, COUNT(*) slot_count
        FROM
           slots
        GROUP BY slot
    ) s ON a.aid = s.sid

    UNION

    SELECT 
        age, age_count, slot, slot_count
    FROM (
        SELECT 
            @m:=@m + 1 AS aid, slot, COUNT(*) slot_count
        FROM
           slots
        GROUP BY slot
    ) a 
    LEFT JOIN (
        SELECT 
            @n:=@n + 1 AS sid, age, COUNT(*) age_count
        FROM
            slots
        GROUP BY age
    ) s ON a.aid = s.sid
) a

如果你确定你拥有比独特插槽更多的独特年龄,或者相反,你可以获得凌乱的联盟。