我有一个名为comparitive_st_sup的表。结构如下:
╔════╦═══════════╦═══════════╦════════╦═══════╗
║ id ║ tender_id ║ item_name ║ ifmain ║ total ║
╠════╬═══════════╬═══════════╬════════╬═══════╣
║ 1 ║ 400 ║ Item 1 ║ Yes ║ 2000 ║
║ 2 ║ 400 ║ Item 2 ║ Yes ║ 2500 ║
║ 3 ║ 400 ║ Item 3 ║ No ║ 2000 ║
║ 4 ║ 400 ║ Item 4 ║ No ║ 2900 ║
║ 5 ║ 400 ║ Item 5 ║ Yes ║ 3100 ║
║ 6 ║ 402 ║ Item 9 ║ Yes ║ 877 ║
║ 7 ║ 402 ║ Item 7 ║ No ║ 9888 ║
╚════╩═══════════╩═══════════╩════════╩═══════╝
现在我需要按照tender_id和ifmain分组并显示总数。例如:
400 Yes 7600 (2000 + 2500 + 3100 that is ifmain=Yes)
400 No 4900 (2000 + 2900 that is ifmain=No)
我尝试了以下查询。但它不起作用:
SELECT
SUM(total) AS maintotal,
SUM(total) AS subtotal, fmain
FROM comparitive_st_sup
WHERE tender_id='$tender_id'
GROUP BY ifmain
答案 0 :(得分:2)
两步GROUP BY
怎么样:
SELECT tender_id, ifmain, SUM(total)
FROM comparative_st_sup
WHERE tender_id='$tender_id' # replace with any WHERE condition you want
GROUP BY tender_id, ifmain
我保留了原始查询中出现的WHERE
子句。如果您将WHERE
条件更改为某个范围,或者将结果集更改为包含多个唯一tender_id
的任何内容,那么我的GROUP BY
就会派上用场。
单击下面的链接以获取查询演示:
<强>更新强>
如果您希望在结果集中将Yes
和No
总和视为单独的列,则可以按以下方式尝试查询:
SELECT tender_id,
SUM(CASE WHEN ifmain = 'Yes' THEN total ELSE 0 END) AS maintotal,
SUM(CASE WHEN ifmain = 'No' THEN total ELSE 0 END) AS subtotal,
FROM comparative_st_sup
WHERE tender_id='$tender_id'
GROUP BY tender_id
同样,您可以更改WHERE
子句以满足您的需要,或者完全删除它。
答案 1 :(得分:0)
分组使用两个字段:
abort