如何在SQL上合并不同数据类型的列?
我有一张桌子:
+-----------+-------------+
+ Column + Data Type +
+-----------+-------------+
+ Day + Int +
+ Time + Varchar +
+ Quota + Int +
+-----------+-------------+
我想合并该表上的所有列。
我尝试了这个,但它不起作用:
SELECT Day + ' - ' + Time + ' : ' + Quota AS [Description], COUNT(*) AS [Total]
FROM table
GROUP BY Day + ' - ' + Time + ' : ' + Quota
错误消息:Data Conversion Failed. [ OLE DB status value (if known) = 2 ]
当我尝试仅合并相同的数据类型时,即:Day
和Quota
,这是有效的。我怎样才能做到这一点?
答案 0 :(得分:4)
数据类型int的列应转换或类型转换为字符串数据类型,如VARCHAR
,以执行字符串连接。
Click this link to view the demo in SQL Fiddle.
脚本:在SQL Server 2012中测试。
CREATE TABLE dbo.MyTable
(
[Day] int NOT NULL
, [Time] varchar NOT NULL
, [Quota] int NOT NULL
);
INSERT INTO dbo.MyTable ([Day], [Time], [Quota]) VALUES
(1, '2', 101),
(1, '1', 101),
(2, '3', 101),
(2, '3', 101),
(3, '4', 263);
SELECT Description
, COUNT(Description) AS DescriptionCount
FROM
(
SELECT CAST([Day] AS VARCHAR)
+ ' - ' + Time
+ ' : ' + CAST([Quota] AS VARCHAR) AS [Description]
FROM dbo.MyTable
) T1
GROUP BY Description;
输出:
DESCRIPTION DESCRIPTIONCOUNT
----------- ----------------
1 - 1 : 101 1
1 - 2 : 101 1
2 - 3 : 101 2
3 - 4 : 263 1
SQL Compact Edition版本的查询:
SELECT LTRIM(RTRIM(STR(Day))) + ' - ' +
LTRIM(RTRIM(Time)) + ' : ' +
LTRIM(RTRIM(STR(Quota))) AS Description
, COUNT(*) AS DescriptionCount
FROM MyTable
GROUP BY LTRIM(RTRIM(STR(Day))) + ' - ' +
LTRIM(RTRIM(Time)) + ' : ' +
LTRIM(RTRIM(STR(Quota)))
输出:
答案 1 :(得分:3)
这是我的答案和Siva的混搭,希望它能解决提问者的问题:
CREATE TABLE MyTable
(
iDay int NOT NULL
, sTime varchar(50) NOT NULL
, iQuota int NOT NULL
);
INSERT INTO MyTable (iDay, sTime, iQuota) VALUES
(1, '2', 101),
(1, '1', 101),
(2, '3', 101),
(2, '3', 101),
(3, '4', 263);
SELECT CAST(iDay AS VARCHAR) + ' - ' + sTime + ' : ' +
CAST(iQuota AS VARCHAR) AS Description
FROM MyTable
GROUP BY CAST(iDay AS VARCHAR) + ' - ' + sTime + ' : ' +
CAST(iQuota AS VARCHAR)
答案 2 :(得分:1)
(假设MySQL):
您正尝试对字符串和整数执行添加操作。 +
不是mysql中的串联运算符。您得到的错误是告诉您该字符串无法转换为数字类型。
试试这个:
SELECT concat(Day, ' - ', Time, ' : ', Quota) AS `[Description]`, COUNT(*) AS `[Total]`
FROM table
GROUP BY `[Description]`
答案 3 :(得分:0)
当您执行GROUP BY时,只需编写字段名称。所以......
选择日+' - '+时间+':'+配额AS [描述],COUNT(*)AS [总计]
从表
GROUP BY日,时间,配额
这有用吗?