我正在根据拖车的长度,门的类型和位置对拖车进行汇总。然后对按门口长度类型分组的记录进行计数,然后上一层并按按门口长度类型分组的拖车进行计数。最后,按批次位置计算拖车总数。
我已经尝试过这个例子;
http://sqlfiddle.com/#!9/23c89e/55
此外,我正在努力使分组和总计正确。这确实可以正确计算拖车的长度(按门类型)-按批次位置。但是,我无法进一步解决该问题。
这是一条选择语句,使我走了这么远。
SELECT g.length, g.doortype, g.location, g.total_location
FROM
( SELECT length, doortype, location, COUNT(*) AS total_location
FROM trailers
GROUP BY length, doortype, location
) AS g
输出示例,此示例按长度,门的类型和位置正确计数,但格式和汇总不正确。
| length | doortype | location | total_location |
|--------|----------|----------|----------------|
| 28FT | ROLL UP | LOT C | 1 |
| 28FT | ROLL UP | LOT D | 2 |
| 28FT | SWING | LOT B | 1 |
| 45FT | ROLL UP | LOT B | 3 |
| 45FT | SWING | LOT B | 1 |
| 48FT | ROLL UP | LOT D | 1 |
| 48FT | ROLL UP | LOT E | 1 |
| 48FT | SWING | LOT A | 6 |
| 48FT | SWING | LOT B | 2 |
| 48FT | SWING | LOT C | 4 |
| 48FT | SWING | LOT E | 2 |
我正在尝试使输出看起来像这样。
| length | doortype | lot a | lot b | lot c | lot d | trailer total|
|--------|----------|-------|-------|-------|-------|--------------|
| 28FT | ROLL UP | 1 | 0 | 1 | 0 | 2 |
| 28FT | SWING | 0 | 0 | 1 | 0 | 1 |
| 45FT | ROLL UP | 1 | 5 | 0 | 0 | 6 |
| 45FT | SWING | 0 | 0 | 0 | 4 | 4 |
| 48FT | ROLL UP | 2 | 1 | 0 | 1 | 4 |
| 48FT | SWING | 0 | 0 | 1 | 1 | 2 |
|------------------------------------------------------------------|
TOTAL | 4 | 6 | 3 | 6 | 19 |
答案 0 :(得分:1)
使用“位置”作为过滤器,并使用总和来合并其计数。
SELECT
length,
doortype,
SUM(IF(location = 'LOT A', 1, 0)) Lot_A,
SUM(IF(location = 'LOT B', 1, 0)) Lot_B,
SUM(IF(location = 'LOT C', 1, 0)) Lot_C,
SUM(IF(location = 'LOT D', 1, 0)) Lot_D,
COUNT(0) AS Trailer_Total
FROM trailers
GROUP BY length, doortype;
答案 1 :(得分:0)
SELECT tab.*
FROM (SELECT
COALESCE(length, 'All length') AS length,
doortype,
SUM(IF(location = 'LOT A', 1, 0)) Lot_A,
SUM(IF(location = 'LOT B', 1, 0)) Lot_B,
SUM(IF(location = 'LOT C', 1, 0)) Lot_C,
SUM(IF(location = 'LOT D', 1, 0)) Lot_D,
COUNT(case location when 'LOT E' then null ELSE 1 end) AS Trailer_Total
FROM trailers
GROUP BY length, doortype WITH ROLLUP
)tab
where tab.doortype IS NOT NULL OR tab.length = 'All length'
order by tab.length, tab.doortype