用于查找重复并获取其他值的SQL查询

时间:2016-03-25 09:33:26

标签: mysql sql count having

这是我的问题。我想找到重复的代码ifls'并获得我获得此重复代码的不同仓库

这就是表格的样子:

| code ifls | warehouse | 
|    4013   |        1  | 
|    4013   |        2  | 
|    4013   |        3  | 
|    4014   |        4  | 
|    4014   |        5  | 
|    4015   |        5  |  

结果应如下所示:

| code ifls | warehouse | warehouse | warehouse |
|    4013   |     1     |     2     |     3     | 
|    4014   |     4     |     5     |           |

我尝试了这个请求但没有成功......

SELECT code ifls as ifls, (SELECT warehouse FROM catalogue WHERE code ifls= ifls) 
FROM catalogue GROUP BY code ifls HAVING COUNT(code ifls) > 1

您如何在SQL查询中表达这一点?

3 个答案:

答案 0 :(得分:0)

您可以使用subselect和group_concat

select `code ifls`, group_concat(warehouse) 
from table  
where `code ifls` in (
    select `code ifls`, count(*)  
    from table 
    group by `code ifls`
    having count(*) > 1
)
group by `code ifls`

答案 1 :(得分:0)

这是你的代码 -

import random

def get_integer(prompt='Enter an integer: ',
                err_prompt='Not an integer, please try again.'):
    answer = input(prompt)
    try:
        return int(answer)
    except ValueError:
        print(err_prompt)
        return get_integer(prompt, err_prompt)

print("Hello, what is your name?")
GG = input()

print("Well, " + GG + ", I am thinking of a number between 0 and 20...")
number = random.randint(0,20)

for taken in range(1,7):
    print("Take a guess.")   
    guess = get_integer()

    if guess < number:
        print("Your guess is too low.")
    elif guess > number:
        print("Your guess is too high.")
    else:
        print("Your guess is exact!")
        break
else:
    print("Too many attempts. You lose!")

答案 2 :(得分:0)

GROUP_CONCAT()可能是您在不使用动态列复杂化的情况下执行操作的最简单方法;

SELECT `code ifls`, GROUP_CONCAT(warehouse) warehouses
FROM myTable
GROUP BY `code ifls`
HAVING COUNT(*) > 1

An SQLfiddle to test with

它基本上为每个code ilfs提供逗号分隔的仓库列表,但HAVING将其限制为具有多个仓库的行。