我试图在一个请求中得到两个请求的结果,这两个后续请求是有效的,并且每个请求都产生一个包含两列的表:
SELECT patron.last_name, COUNT(*) AS **pret**
FROM circ_transaction_log INNER JOIN patron ON circ_transaction_log.patron_id=patron.patron_id
AND **circ_transaction_log.transaction_type<5**
AND patron.college_or_school = 'High School'
GROUP BY patron.last_name;
last_name |的 pret的
________________
史蒂文格雷勒| 552个
米歇尔葡萄酒| 122
...
_________________________ 或 _________________________
SELECT patron.last_name, COUNT(*) AS **resa**
FROM circ_transaction_log INNER JOIN patron ON circ_transaction_log.patron_id=patron.patron_id
AND **circ_transaction_log.transaction_type BETWEEN 5 AND 10**
AND patron.college_or_school = 'High School'
GROUP BY patron.last_name;
last_name |的 RESA
________________
史蒂文格雷勒| 12个
米歇尔葡萄酒| 8
...
我想得到的结果有点像这样:
last_name | resa |的 pret的
_______________________________
史蒂文格雷勒| 552 | 12个
米歇尔葡萄酒| 122 | 8
......
但我认为困难在于我要求同一张桌子两次(表CIRC_TRANSACTION_LOG)以及我尝试的任何内容或错误或不起作用
预先感谢您的回复
此致 Nickk
答案 0 :(得分:1)
你是这样的,然后:
SELECT p.last_name,
COUNT(case when ctl.transaction_type < 5 then 1 end) AS pret,
count(case when ctl.transaction_type between 5 and 10 then 1 end) as resa
FROM circ_transaction_log ctl
INNER JOIN patron p ON (ctl.patron_id = p.patron_id)
AND ctl.transaction_type <= 10 -- possibly not required if transaction_type is always <= 10
AND p.college_or_school = 'High School'
GROUP BY p.last_name;
NB。未经测试,因为您没有为表格提供任何样本数据。
答案 1 :(得分:0)
我更喜欢这种方法。如果该行符合您的条件,请在列中添加1,如果它不匹配,则将0添加。然后,当您将所有值相加时,它会为您提供匹配的行数。这允许您为不同的条件创建不同的总和。
SELECT
PatronCounts.last_name,
SUM(PatronCounts.Pret) Pret,
SUM(PatronCounts.Resa) Resa
FROM
(SELECT
patron.last_name,
CASE WHEN circ_transaction_log.transaction_type < 5 THEN 1 ELSE 0 END AS Pret,
CASE WHEN circ_transaction_log.transaction_type BETWEEN 5 AND 10 THEN 1 ELSE 0 END AS Resa,
FROM
circ_transaction_log
INNER JOIN patron ON circ_transaction_log.patron_id=patron.patron_id
WHERE
patron.college_or_school = 'High School'
GROUP BY
patron.last_name) PatronCounts
答案 2 :(得分:0)
您可以使用(last_name)对结果表的完全外部联接组合您的查询。这应该产生预期的结果。试图创建查询...
Select * from
(SELECT patron.last_name, COUNT(*) AS pret
FROM circ_transaction_log INNER JOIN patron ON circ_transaction_log.patron_id=patron.patron_id
AND circ_transaction_log.transaction_type<5
AND patron.college_or_school = 'High School'
GROUP BY patron.last_name)
FULL OUTER JOIN
(SELECT patron.last_name, COUNT(*) AS resa
FROM circ_transaction_log INNER JOIN patron ON circ_transaction_log.patron_id=patron.patron_id
AND circ_transaction_log.transaction_type BETWEEN 5 AND 10
AND patron.college_or_school = 'High School'
GROUP BY patron.last_name)
USING (last_name)