|
我绝对是SQL的新手,我一直在努力用Postgresql中的以下表结构编写一个复杂的查询:! b9 l7 t7 k2 t
CREATE TABLE reports
$ n; g+ y- n3 G! J# d(
# |0 t' N/ M# Z6 |1 R- X, H reportid character varying(20) NOT NULL,( g( L: h( Q1 l u& Q
userid integer NOT NULL,9 Z. s2 k4 [$ |* p
reporttype character varying(40) NOT NULL, 1 `: J% h% u- M% Y, o6 K+ ?
)- Y# z+ ?& a0 L+ T0 o4 @$ E
CREATE TABLE users3 c3 C3 A" ~" p/ e
(( c8 `. n" Y4 ?+ ^( E C# g" ], k
userid serial NOT NULL,
8 B5 N4 ~ J: v8 \( } username character varying(20) NOT NULL,/ U% M- n8 B+ ^# i2 `+ H m* [ d
)( K4 J* c e% O9 ]' o( v% p
查询的目的是获取每个用户的报告类型数量,并将其显示在一列中。有三种不同类型的报告。
0 ?* ?: k4 O+ ?使用group-by的简单查询将解决问题,但将其显示在不同的行中:2 V- {0 E6 \/ o! w: G; C0 v; i
select count(*) as Amount,. g* H( ~/ ]) |4 ?% |' u
u.username,
- ]+ u7 O) |$ F' s r.reporttype 5 g, ~* O$ T a4 I; e$ d
from reports r,
6 x! z& R! x( z5 x users u
u X) U7 j- S% Z! N+ w6 vwhere r.userid=u.userid
( H" `8 w' k3 j* @& U9 zgroup by u.username,r.reporttype
: n( l/ z! Z. o8 D) |& L& `order by u.username- J, J4 r$ @+ Q& o" _: K# B) J% t
/ W2 d' Z& w; P& y# o: A
解决方案:- F- |! C" X& O# u J. q
, M: K$ X+ w; Q- t; H. k
" X7 Y1 o7 b5 N' M
$ z9 l( m |' H SELECT$ X" z7 D3 r. r# v# D- B
username,- Q# ]$ C" T. U: j# {) R |, j1 Z. ]3 z
(4 \' d3 x9 v& I9 a' J
SELECT & c9 i& d! u6 |4 T, p3 b+ n% X
COUNT(*)$ ?1 A, D9 Q) l! s
FROM reports " u& K/ p* Q ?. Z+ y
WHERE users.userid = reports.userid && reports.reporttype = 'Type1'
* ]1 e: q3 ]* ^& |0 P ) As Type1,
/ f/ r! k2 [/ g5 M- W7 \9 i6 v (
4 g' t7 a: j- w! b9 L+ e8 o4 N SELECT
1 i$ f5 a9 j; A$ t+ v* r: V1 ~ COUNT(*)0 y3 C6 o4 n3 ~0 Y
FROM reports
/ L- B b5 H, \4 v3 [) U WHERE users.userid = reports.userid && reports.reporttype = 'Type2'
o2 A+ r+ g- W ) As Type2,
4 A: Q7 ^/ d$ P& V& ], p c* ^9 B (
2 d- P l% d. l/ P SELECT 6 ]: D% \4 r8 ^; v9 b
COUNT(*), D2 m: t: n: D% Y! ~% @
FROM reports / l5 K$ t. ~( p, l* p3 ~& v
WHERE users.userid = reports.userid && reports.reporttype = 'Type3'5 [: G8 b6 a/ ?; A( ~
) As Type38 |, N: K5 j! m: D) m7 U4 T2 u
FROM
* Y& I/ l+ y0 k( V1 d- v$ X users+ t, n: C! I s6 [. y5 j
WHERE
+ k) |: Z$ Z) k' l2 ~ EXISTS(
: g# L9 w. e; B; K) ~6 {2 u SELECT & u0 k; e1 x! j7 T
NULL2 d" o) F4 ^$ d: b
FROM ; V `4 V. {! q& h) h4 ]
reports8 Q: w' s, p& r
WHERE
4 |% e! D' \) x users.userid = reports.userid
3 Q4 b* M* u, i& a5 O ) |
|