gpt4 book ai didi

mysql - 在 MYSQL 5.1 中使用@DECLARE

转载 作者:行者123 更新时间:2023-11-29 13:56:20 25 4
gpt4 key购买 nike

只是在 MYSQL Server 5.1 上玩一些 sql 语句我已经问了一个问题如何对两个表进行具体计数(请参阅 here )我还找到了如何转置结果的答案(请参阅 here ),但我无法在本地 MYSQL Server 5.1 上使用它。

这是表一:测试

id|name|test_type
-------------
1|FirstUnit|1
2|FirstWeb|2
3|SecondUnit|1

第二个表:test_type

id|type
--------
1|UnitTest
2|WebTest

以下结果将写入“yourtable”(临时表)

type|amount
-----------
UnitTest|2
WebTest|1

我最后想要的是:

UnitTest|WebTest
-----------------
2|1

(问题是我认为,最后一部分来自 MS-SQL 示例,因此它不适用于 MYSQL)

这是我的sql语句:

--create a temporary table
create temporary table IF NOT EXISTS yourtable
(
test_type varchar(255),
amount varchar(255)
);

--make a selecten into the temporary table
INSERT INTO yourtable
SELECT
t.test_type ,
COUNT(*) AS amount

FROM test_types AS t
JOIN test AS te ON t.id= te.test_type
GROUP BY test_type
ORDER BY t.test_type;


--just for debugging
select * from yourtable;


-- transpose result
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Type)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')

set @query = 'SELECT ' + @cols + ' from
(
select Type, Amount,
row_number() over(partition by Type order by Type, Amount) rn
from yourtable
) x
pivot
(
max(Amount)
for Type in (' + @cols + ')
) p '

execute(@query)

--drop temporary table
drop table yourtable;

我无法运行我想要转置临时结果的最后一部分。我收到“DECLARE”错误

/* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)

select @cols = ' at line 2 / / 2 rows affected, 2 rows found. Duration for 3 of 4 queries: 0,000 sec. */

有人可以帮忙吗?

最佳答案

MySQL 没有pivot函数,因此您必须使用带有CASE表达式的聚合函数将数据从行转置为列:

select 
sum(case when tt.type = 'UnitTest' then 1 else 0 end) UnitTest,
sum(case when tt.type = 'WebTest' then 1 else 0 end) WebTest
from test t
inner join test_type tt
on t.test_type = tt.id

参见SQL Fiddle with Demo .

如果您想要将未知数量的类型转换为列,则可以使用准备好的语句来生成动态 SQL:

SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'sum(CASE WHEN tt.type = ''',
type,
''' THEN 1 else 0 END) AS `',
type, '`'
)
) INTO @sql
FROM test_type;

SET @sql
= CONCAT('SELECT ', @sql, '
from test t
inner join test_type tt
on t.test_type = tt.id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

参见SQL Fiddle with Demo

关于mysql - 在 MYSQL 5.1 中使用@DECLARE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15810987/

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