半复杂SQL到Django ORM中,在WHERE,COUNT和DISTINCT中使用SELECT

时间:2015-10-09 01:40:38

标签: sql django orm

这是我想要转换成Django ORM代码的一些SQL。如果我必须使用raw()或extra(),那就没问题。

我在这里有一个SQL小提琴http://sqlfiddle.com/#!15/14118/8

架构:

CREATE TABLE box (
  num int,
  group1 char(8),
  group2 char(8)
);

INSERT INTO box (num, group1, group2) VALUES 
  (4,  'group_a','group_ab'),
  (8,  'group_a', 'group_ab'),
  (12, 'group_a', 'group_ab'),
  (4,  'group_b', 'group_ab'),
  (8,  'group_c', 'group_cd'),
  (16, 'group_a', 'group_ab'),
  (16, 'group_b', 'group_ab');

第一种情况,我只想要匹配group1值的结果数量超过数字的结果(这里是' s' 2')。

SELECT *
FROM box
WHERE (SELECT COUNT(*) 
   FROM box as b
   WHERE group1 = box.group1
) > 2;

输出:

| num |   group1 |   group2 |
|-----|----------|----------|
|   4 | group_a  | group_ab |
|   8 | group_a  | group_ab |
|  12 | group_a  | group_ab |
|  16 | group_a  | group_ab |

第二种情况,我只想要匹配group2值的结果数量超过数字的结果(这里是' 4')。我也只想要结果,正好有两行共享相同的数字' num'值。最后,我希望结果与“数字”不同。列。

SELECT DISTINCT on (num) *
FROM box
WHERE (SELECT COUNT(*)
   FROM box as b
   WHERE group2 = box.group2
   ) > 4
AND (SELECT COUNT(*)
   FROM box as b
   WHERE group2 = box.group2
   AND num = box.num
   ) = 2

输出:

| num |   group1 |   group2 |
|-----|----------|----------|
|   4 | group_a  | group_ab |
|  16 | group_a  | group_ab |

0 个答案:

没有答案