首页 > 解决方案 > 在 WHERE 子句中添加条件会产生更多结果

问题描述

我使用 SqlServer。我有一张有很多列的表,其中重要的是:

· 用户名

· 分区 - xxxx-xx-xx 格式的日期

· 游戏 - 用作 ID 的字符串

· 学分 - 一个数字

· 投注 - 另一个号码

· 奖品 - 另一个号码

· Num_Spins - 另一个数字

我写了一个查询来选择给定特定日期我感兴趣的那些。

Select distinct CONCAT(User_Name, DATALENGTH(User_Name)) as User_name, Partition, Game, Bet, Num_spins, Credits, Prize
            from ***
            where Partition>='2019-09-01' and Partition<'2019-11-17' and Bet>0 and credits is not null
            and User_Name IN (Select distinct userName from *** where GeoIpCountryCode='ES')

我希望我能把它变成一个视图或其他东西,但不幸的是我没有这样做的特权。因此,我从中做了一个子查询:

我想从这些行中找出其数字遵循某个数学结果的行:(Credits+Bet-Prize) > 100000 and num_spins>5

Select user_name, partition, count(Game) as difMachines
        FROM
        (
            Select distinct CONCAT(User_Name, DATALENGTH(User_Name)) as User_name, Partition, Game, Bet, Num_spins, Credits, Prize
            from ***
            where Partition>='2019-09-01' and Partition<'2019-11-17' and Bet>0 and credits is not null
            and User_Name IN (Select distinct userName from *** where GeoIpCountryCode='ES')
        ) as A
        where 
        (Credits+Bet-Prize) > 100000 and num_spins>5
        group by User_Name, Partition;

现在,我得到了我需要的所有信息。我运行最后一个查询,以 group_by 日期这些结果,以便我可以分析它们:

Select  datepart(week,Partition) as Week, count (distinct user_name) as Users
    from (
        Select user_name, partition, count(Game) as difMachines
        FROM
        (
            Select distinct CONCAT(User_Name, DATALENGTH(User_Name)) as User_name, Partition, Game, Bet, Num_spins, Credits, Prize
            from ***
            where Partition>='2019-09-01' and Partition<'2019-11-17' and Bet>0 and credits is not null
            and User_Name IN (Select distinct userName from *** where GeoIpCountryCode='ES')
        ) as A
        where 
        (Credits+Bet-Prize) > 100000 and num_spins>5
        group by User_Name, Partition
    ) as B
    Where difMachines=1
    group by datepart(week,Partition)
    order by Week asc;

我知道查询可以优化,但这不是我的困扰。问题是在运行此查询时,我在第 36 周获得了 17050 个用户。如果我(Credits+Bet-Prize) > 100000 and num_spins>5为这一行更改这一行(Credits+Bet-Prize) > 100000(因此,我纯粹删除了该num_spins>5部分),我将获得 16800 个用户。

总而言之,通过对查询进行更多限制,我得到了更多结果。这对我来说没有意义。有人可以帮忙吗?带我去正确的方向还是什么?

谢谢

标签: sql-servergroup-bysubquerywhere-clause

解决方案


您正在尝试使用此过滤器diffmachine=1获取结果集的计数,不是吗?但是如果您删除过滤器num_spins>5则计数将增加diffmachine大于 1.here 我举一个像你这样的例子

Declare  @t table
(
    [user_name] varchar(5), [partition] date, Game varchar(10),num_spins int
)

insert into @t
select 'a','01nov19','g1',1
union all
select 'a','01nov19','g1',2
union all
select 'a','01nov19','g1',3
union all
select 'a','01nov19','g1',4
union all
select 'a','01nov19','g1',5
union all
select 'a','01nov19','g1',6
union all
select 'b','01nov19','g1',7

select * from
(
    select [user_name],[partition],count(game) cnt
    from  @t
    where num_spins>5
    group by [user_name],[partition]
)a
where cnt=1

推荐阅读