zoukankan      html  css  js  c++  java
  • 一个SQL语句的实现

    学生表student

    stuid   name   age

    01      xp      20
    02      pan     12


    学生属性表

    id      stuid          type

    1          01           A
    2          01           b
    3          01           C
    4          02           A
    5          02           C


    如何得到type是既是A、又是B、又是C的学生(即01号学生)。

    依次类推,如何根据客户对type的输入,得到相应的查询记录。比如客户输入A、C就得到既是A又是C的学生(即01和02),客户输入A、B就得既是A、又是B的学生(即01)


    解答:

    --創建測試環境
    Create Table 学生属性表
    (id Int,
     stuid Char(2),
     type Varchar(10))
    --插入數據
    Insert 学生属性表 Select 1,          '01',           'A'
    Union All Select 2,          '01',           'b'
    Union All Select 3,          '01',           'C'
    Union All Select 4,          '02',           'A'
    Union All Select 5,          '02',           'C'
    GO
    --測試
    Declare @type Varchar(1000)
    Select @type = 'A,B,C'
    Select stuid From 学生属性表 Where CharIndex(type, @type) > 0 Group By stuid Having Count(stuid) = Len(@type) - Len(Replace(@type, ',', '')) + 1

    Select @type = 'A,C'
    Select stuid From 学生属性表 Where CharIndex(type, @type) > 0 Group By stuid Having Count(stuid) = Len(@type) - Len(Replace(@type, ',', '')) + 1
    GO
    --刪除測試環境
    Drop Table 学生属性表
    --結果
    /*
    stuid
    01

    stuid
    01
    02
    */

  • 相关阅读:
    中缀表达式求值
    520的信心赛——点点玩deeeep
    520的信心赛——麓麓学数学
    l洛谷 (水题)P4144 大河的序列
    洛谷 P3391 【模板】文艺平衡树(Splay)
    在洛谷3369 Treap模板题 中发现的Splay详解
    洛谷 P1344 [USACO4.4]追查坏牛奶Pollutant Control
    洛谷 P1678 烦恼的高考志愿
    洛谷 P2421 A-B数对(增强版)
    P3381 【模板】最小费用最大流
  • 原文地址:https://www.cnblogs.com/xp/p/874212.html
Copyright © 2011-2022 走看看