提前sql查询

时间:2015-06-07 20:18:25

标签: sql join

如何在这种情况下构建SQL查询:

我必须使用表格(仅显示表格列)

表一

public static Collector<Integer, List<Integer>, Stream<Integer>> intDifferences() {

    return new Collector<Integer, List<Integer>, Stream<Integer>>() {

        @Override
        public BiConsumer<List<Integer>, Integer> accumulator() {
            return List::add;
        }

        @Override
        public Set<Collector.Characteristics> characteristics() {
            return EnumSet.noneOf(Collector.Characteristics.class);
        }

        @Override
        public BinaryOperator<List<Integer>> combiner() {
            return (left, right) -> {
                left.addAll(right);
                return left;
            };
        }

        @Override
        public Function<List<Integer>, Stream<Integer>> finisher() {
            return list -> {
                List<Integer> differences = new ArrayList<>();
                for (int i = 1; i < list.size(); i++) {
                    differences.add(list.get(i) - list.get(i - 1));
                }
                return differences.stream();
            };
        }

        @Override
        public Supplier<List<Integer>> supplier() {
            return ArrayList::new;
        }
    };
}

表二

- Users -> ID, First name, Last name....

我想得到这样的SQL结果:

– events -> ID, UserID, statID

请帮帮我

1 个答案:

答案 0 :(得分:4)

这是一个基于sql server的解决方案:

SELECT u.ID, 
       u.[First Name],
       u.[Last Name],
       SUM(CASE WHEN e.statID = 11 AND e.date >= date1 AND e.date<= date2 
                THEN 1
                ELSE 0
           END) AS CountStat11, 
       SUM (CASE WHEN e.StatID= 8 AND e.date >= date1 AND e.date<= date2 
                 THEN 1
                 ELSE 0
            END) AS CountStat8
FROM users AS u LEFT JOIN events AS e ON u.ID = e.userid
GROUP BY u.ID, u.[First Name], u.[Last Name]

在这里,我使用LEFT JOIN为所有用户提供结果,即使他们没有任何事件。如果您只对那些有活动ID的人感兴趣,那么您需要使用INNER JOIN