gpt4 book ai didi

sql - T-SQL通过by子句进行分组

转载 作者:行者123 更新时间:2023-12-02 06:03:59 25 4
gpt4 key购买 nike

 Masterid    CC  CLA DES NLCLA   NLDES
-------------------------------------
53006141 CN 0 0 1 1
53006141 US 1 1 1 1
53006141 UK 1 1 0 0
53006142 US 1 1 0 0
53006142 UK 1 1 0 0
53006143 CN 0 0 1 1
53006143 US 1 1 0 0
53006143 UK 1 1 0 0

根据以上数据,我需要产生
  • 包含MasterIdsCC = USCC = CNNLCLA = 1NLDES = 1列表

  • 输出应为
    53006141
    53006143

    MasterID下必须同时包含CN和US。

    有人可以帮我用SQL做到这一点吗?

    最佳答案

    您可以通过添加WHERE子句来执行此操作,该子句将返回带有USCN的行:

    select distinct Masterid
    from yourtable
    where cc in ('US', 'CN')
    and NLCLA = 1
    AND NLDES = 1

    参见 SQL Fiddle with Demo

    如果希望结果同时包含 CNUS,则可以使用:
    select Masterid
    from yourtable
    where cc in ('US', 'CN')
    and NLCLA = 1
    AND NLDES = 1
    group by masterid
    having count(distinct cc) = 2

    参见 SQL Fiddle with Demo

    可以完成此操作的另一种方法是使用 EXISTS来获取同时具有 USCN的MasterId列表。然后,将其他过滤器放置在 WHERE子句中,而不是子查询中。
    select distinct masterid
    from yourtable t1
    where exists (select Masterid
    from yourtable t2
    where cc in ('US', 'CN')
    and t1.masterid = t2.masterid
    group by masterid
    having count(distinct cc) = 2)
    and NLCLA = 1
    and NLDES = 1;

    参见 SQL Fiddle with Demo

    关于sql - T-SQL通过by子句进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14835577/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com