我有一个查询,我无法将最后一行columb名称的名称更改为' TOTAL'。结果给出了与最后一行上方行相同的名称。 这是我的疑问:
SELECT COALESCE(ticket_types.name,'TOTAL') AS name,
COUNT(1) AS quantity
FROM tr_logs
LEFT JOIN tickets ON tr_logs.value = tickets.id
LEFT JOIN ticket_types ON tickets.ticket_type_id = ticket_types.id
LEFT JOIN transactions ON tr_logs.transaction_id = transactions.id
LEFT JOIN tr_fields_data AS tfd_shipping ON tfd_shipping.transaction_id = transactions.id
WHERE type = 'ADDITEM'
AND transactions.event_id = '46'
AND DATE(tr_logs.created_date)
BETWEEN '2017-03-26' AND '2017-05-24'
AND tfd_shipping.data IN ('0','570','571','771')
AND name IS NOT NULL
GROUP BY ticket_types.id WITH ROLLUP
结果如下:
name quantity
premium 56
outlaw 6
outlaw 62
汇总的最后一行名称不为空....我需要它是TOTAL而不是outlaw
由于
答案 0 :(得分:1)
您还没有将名称更改为TOTAL
:您已将列名更改为name
,并且您已将其更改为“{1}}”带有TOTAL
的空值。
如果您想将ticket_types.name
的名称更改为total
,您只需要
SELECT ticket_types.name AS total ...
(但将名为name
的内容重命名为total
会很奇怪,所以您可能需要稍微澄清一下您的要求。)
答案 1 :(得分:0)
这可能与您观察到的问题有关,但WHERE
和GROUP BY
子句将所有外连接转换为内连接。您应该将查询简化为:
SELECT COALESCE(tt.name, 'TOTAL') AS name, COUNT(1) AS quantity
FROM tr_logs l JOIN
tickets
ON l.value = t.id JOIN
ticket_types tt
ON t.ticket_type_id = tt.id JOIN
transactions tr
ON l.transaction_id = tr.id JOIN
tr_fields_data fd
ON fd.transaction_id = tr.id
WHERE type = 'ADDITEM' AND
tr.event_id = '46' AND
DATE(l.created_date) BETWEEN '2017-03-26' AND '2017-05-24' AND
fd.data IN ('0', '570', '571', '771') AND
tt.name IS NOT NULL
GROUP BY tt.id WITH ROLLUP
答案 2 :(得分:0)
感谢Gordon Linoff,我已经弄清楚了我的问题。
最后一行的名称永远不会为null,因为我的GROUP BY具有不同的属性。
这是解决方案。
SELECT COALESCE(tckn,'TOTAL') AS name, quantity FROM
(SELECT tt.name AS tckn, COUNT(1) AS quantity
FROM tr_logs AS l
LEFT JOIN tickets AS t ON l.value = t.id
LEFT JOIN ticket_types AS tt ON t.ticket_type_id = tt.id
LEFT JOIN transactions AS tr ON l.transaction_id = tr.id
LEFT JOIN tr_fields_data AS tfd ON tfd.transaction_id = tr.id
WHERE type = 'ADDITEM'
AND tr.event_id = '46'
AND DATE(l.created_date)
BETWEEN '2017-03-26' AND '2017-05-24'
AND tfd.data IN ('0','570','571','771')
GROUP BY tckn WITH ROLLUP) as sum;