且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-26 22:05:52

你的要求有点奇怪.你确定要那个吗?

Your request is kind of odd. Are you sure you want that?

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

If so, this may help:

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

如果你确定你有更多的独特年龄而不是独特的插槽,或者相反,你可以摆脱混乱的联盟.

If you know for sure that you have more unique ages than unique slots , or opposite, you can get ride of messy union.