根据SELECT语句结果创建表

时间:2013-07-03 15:55:43

标签: sql

我是这个网站的新手,也是SQL的新手。我希望你能帮忙。我创建了以下SQL查询。我现在想创建一个新表并将查询结果传输到这个新表中。

是否可以在以下查询中添加语法以自动创建表?


SELECT
    Value [Value],
        DateTime [DateTime], 
            DatePart (Week, DateTime) [WeekNumber],
                hs.StorageItemID [StorageItemId]

FROM History_StorageItem hs

    JOIN History_Float hf ON hs.StorageItemId = hf.StorageItemId

GROUP BY DatePart (Week,DateTime), hs.StorageItemId, Value
ORDER BY hs.StorageItemId DESC

此外,与DateTime相关的此查询的结果是返回yyyy-mm-dd hh:mm:ss ......是否可以从我的查询和数据添加到的结果值中删除时间我的桌子只是“日期”。

我非常感谢您的支持,因为我对SQL的有限知识到目前为止只能把我带走。

感谢。

5 个答案:

答案 0 :(得分:1)

答案可能因RDBMS而异。您可以使用INTOSELECT结果创建表格,然后将DATETIME转换为DATE

SELECT
    Value [Value],
        CAST (DateTime AS DATE) [DateTime], 
            DatePart (Week, DateTime) [WeekNumber],
                hs.StorageItemID [StorageItemId]
INTO newTable
FROM History_StorageItem hs

    JOIN History_Float hf ON hs.StorageItemId = hf.StorageItemId

GROUP BY DatePart (Week,DateTime), hs.StorageItemId, Value
ORDER BY hs.StorageItemId DESC

答案 1 :(得分:0)

确保在FROM

之前只能选择INTO子句
SELECT Value [Value], DateTime [DateTime], DatePart (Week, DateTime) [WeekNumber], hs.StorageItemID [StorageItemId]
INTO [TABLENAME]
FROM History_StorageItem hs

JOIN History_Float hf ON hs.StorageItemId = hf.StorageItemId
GROUP BY DatePart (Week,DateTime), hs.StorageItemId, Value ORDER BY hs.StorageItemId DESC

我推荐你这些教程

http://www.w3schools.com/sql/sql_select_into.asp

答案 2 :(得分:0)

create table YOURTABLENAME AS
SELECT
    Value [Value],
        DateTime [DateTime], 
            DatePart (Week, DateTime) [WeekNumber],
                hs.StorageItemID [StorageItemId]

FROM History_StorageItem hs

    JOIN History_Float hf ON hs.StorageItemId = hf.StorageItemId

GROUP BY DatePart (Week,DateTime), hs.StorageItemId, Value
ORDER BY hs.StorageItemId DESC

答案 3 :(得分:0)

另一方面,如果你想创建一个视图而不是一个表,你可以这样做:

CREATE VIEW [newView] AS
SELECT
Value [Value],
    DateTime [DateTime], 
        DatePart (Week, DateTime) [WeekNumber],
            hs.StorageItemID [StorageItemId]
FROM History_StorageItem hs
JOIN History_Float hf ON hs.StorageItemId = hf.StorageItemId
GROUP BY DatePart (Week,DateTime), hs.StorageItemId, Value

答案 4 :(得分:0)

您应该使用日期格式化方法,这些方法会根据您的sql server类型进行更改

Postgres

MySQL

Oracle