1

如何在 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 ]

当我尝试仅合并相同的数据类型时,即:Dayand Quota,它的工作。我怎样才能做到这一点?

4

4 回答 4

4

应将数据类型 int 的列转换或类型转换为字符串数据类型,例如VARCHAR执行字符串连接。

单击此链接以查看 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)))

输出

sql ce 输出

于 2012-04-29T02:36:47.160 回答
3

这是我的答案和 Siva 的混搭,希望它能解决提问者的问题:

SQL 小提琴链接

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)
于 2012-04-29T03:08:10.130 回答
1

(假设 MySQL)

您正在尝试对字符串和整数执行加法。+不是 mysql 中的连接运算符。您得到的错误是告诉您无法将字符串转换为数字类型。

尝试这个:

SELECT concat(Day, ' - ', Time, ' : ', Quota) AS `[Description]`, COUNT(*) AS `[Total]`
FROM table
GROUP BY `[Description]`
于 2012-04-29T02:34:42.147 回答
0

当您执行 GROUP BY 时,只需编写字段名称。所以...

SELECT Day + ' - ' + Time + ' : ' + Quota AS [Description], COUNT(*) AS [Total]
FROM table GROUP BY Day, Time, Quota

那样有用吗?

于 2012-04-29T02:27:33.823 回答