gpt4 book ai didi

mysql - 如何在 MySQL 中获取 DISTINCT 列和列的 COUNT?

转载 作者:行者123 更新时间:2023-11-29 01:38:59 25 4
gpt4 key购买 nike

我不知道如何为以下问题编写查询。

我正在使用以下查询

SELECT * FROM
(
SELECT cont_details.*,
location.location,
depot_details.depot_name as depot_name,
depot_details.depot_code as depot_code,
block.block_id,
depot_details.depot_city,

depot_tracking.depot_tracking_id as depot_tracking_id

FROM depot_tracking

LEFT JOIN depot_details
ON depot_tracking.depot_details_id = depot_details.depot_details_id

LEFT JOIN cont_details
ON depot_tracking.cont_details_id = cont_details.cont_details_id

LEFT JOIN block
ON depot_tracking.cont_details_id = block.cont_details_id

LEFT JOIN cont_sold
ON depot_tracking.cont_details_id = cont_sold.cont_details_id

LEFT JOIN location
ON depot_details.depot_city = location.port_code

WHERE
depot_tracking.status = "0"
AND depot_tracking.gate_out =""
AND block.block_id IS NULL
AND cont_sold.cont_sold_id IS NULL

ORDER BY
cont_details.cont_details_id ASC,
str_to_date(depot_tracking.gate_in,"%d-%m-%Y") DESC
)
origin GROUP BY origin.cont_details_id

这个查询的输出是 SHOW BELOW(只是列名会改变的例子)

 ------------------------------------------
location | size | type | price |
-------------------------------------------
USA | 20 | GP | 230 |
USA | 20 | GP | 330 |
UAE | 40 | HD | 230 |
IND | 40 | RF | 230 |
IND | 30 | FR | 430 |
IND | 40 | FR | 870 |
USA | 30 | HD | 230 |
UAE | 40 | RF | 430 |
USA | 30 | GP | 230 |
UAE | 20 | HD | 445 |
UAE | 20 | RF | 323 |
IND | 30 | FR | 130 |
-------------------------------------------

现在,我需要从此表中获取不同的位置并根据位置、大小和类型列进行计数。示例如下所示。

     --------------------------------------------------------------------------------
location | 20GP | 20HD | 20RF | 30FR | 30HD | 30GP | 30GP | 40HD | 40FR | 40RF |
--------------------------------------------------------------------------------
UAE | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 1 |
USA | 2 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 |
IND | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 1 | 1 |
--------------------------------------------------------------------------------

最佳答案

SELECT 
Mtab.location,
SUM(CASE WHEN ( Mtab.size='20' AND Mtab.type='GP') THEN 1 ELSE 0 END) AS '20GP',
SUM(CASE WHEN ( Mtab.size='20' AND Mtab.type='HS') THEN 1 ELSE 0 END) AS '20GP',
SUM(CASE WHEN ( Mtab.size='20' AND Mtab.type='RF') THEN 1 ELSE 0 END) AS '20GP',
(
your current query...
your current query...
your current query...
)
Mtab
GROUP BY Mtab.location

关于mysql - 如何在 MySQL 中获取 DISTINCT 列和列的 COUNT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31200604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com