【问题标题】:SQL query to get count of distinct values of columns in a same tableSQL查询以获取同一表中列的不同值的计数
【发布时间】:2022-10-08 01:07:02
【问题描述】:

我有表格,其中包含性别、状态等列。

表值是这样的

ID Gender Status
1 Male A01
2 Male
3 Female A02
4 Female
5 Unknown
6 Male
7 Female
8 Unknown

我要显示

Gender Status Count
Male A01 1
Female A02 1
Unknown 0

我试过了

SELECT 
    t3.Gender, t3.Status, COUNT(*) AS count 
FROM
    (SELECT DISTINCT
         t1.Gender, t1.Status 
     FROM 
         Consumer AS t1
     CROSS JOIN 
         Consumer AS t2 
     WHERE 
         t1.Status <> t2.Status 
         OR t1.Status <> t2.Status) AS t3 
GROUP BY
    t3.Gender, t3.Status

请帮助解决这个问题。谢谢

【问题讨论】:

  • 所以计数仅适用于具有地位价值的性别?
  • 我不明白在这里使用交叉连接。
  • 目前尚不完全清楚您想要什么行为。您应该扩展您的示例以显示可能出现的各种可能的数据组合,然后显示您想要的结果。目前我可以给出十几个给出这些结果的查询,但不知道它们是否一般有用。
  • @MatBailie——一打?这似乎很多——可能是 3 或 4 个

标签: sql sql-server


【解决方案1】:

据我所知,这只是一组

SELECT gender, status, count(*) as [count]
FROM consumer
GROUP BY gender, status

唯一的问题是您是否要计算所有状态值。 EG 如果男性也有 A02,那么您需要 2 个。如果这是您的目标,那么您对该行的状态列有什么期望。

【讨论】:

  • 这个查询给出了错误的答案。如果有相同性别的status is not null,op 不希望显示status is null
  • 什么?我的查询不这样做吗?你在说什么?
【解决方案2】:

你可能想多了你的要求。也许以下方法会起作用:

SELECT Gender, Status, COUNT(*) AS count
FROM Consumer
GROUP BY Gender, Status
ORDER BY Gender, Status

目前尚不清楚您对未知性别的结果有何期望。

【讨论】:

    【解决方案3】:
    select  gender
           ,status
    from    (
            select   distinct gender
                    ,status                                                                                                                                                                                                                               as status
                    ,case when count(case when status is not null then 1 end) over(partition by gender) > 0 and status is not null then 1 when count(case when status is not null then 1 end) over(partition by gender) = 0 and status is null then 1 end as mrk
            from     t
            ) t
    where   mrk = 1
    
    gender status count
    Female A02 1
    Male A01 1
    Unknown null 0

    Fiddle

    【讨论】:

    • 你为什么假设他们想要 MAX 作为状态列?
    • @Hogan 查看更新的答案
    • 好的,现在它是一个总的吧?两个屏幕的最后格式化????
    • @hogan 我不知道你在问什么。
    猜你喜欢
    • 2021-06-06
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多