6
votes

Comment récupérer la partie de date d'une colonne de résultat DateTime dans SQLite?

J'ai une colonne de type DateTime à partir de laquelle je voudrais récupérer seulement la date. Y a-t-il de toute façon pour faire cela?

C'était précédemment une valeur d'époque où je le convertit je le converti en DateTime. P>

Voici un résultat d'échantillon: P>

SELECT DATE(datetime) from attacked_total;
SELECT STRFTIME('%Y-%m-%d', datetime) FROM attacked_total;
SELECT DATETIME('%Y-%m-%d', datetime) FROM attacked_total;
SELECT DATE('%Y-%m-%d', datetime) FROM attacked_total;


0 commentaires

4 Réponses :


0
votes

Essayez d'utiliser l'utilisation de la fonction "DatePart" dans SQL.

Quelque chose comme ça devrait fonctionner: p>

SELECT datewithouttime as datepart(dd,datefield)+'/'+datepart(mm,datefield)+"/"+datepart(yyyy,datefield) FROM tableName


4 commentaires

Sélectionnez DatePart (DD, Datefield) + '/' + DatePart (MM, Datefield) + "/" + DatePa RT (aaaaa, Datefield) en tant que dateWithOutTime de Tablename


Hmm, je ne comprends pas bien vos codes. J'ai une colonne nommée DateTime pour récupérer uniquement les dates et une table nommée attaquée_totale. J'ai donc modifié vos requêtes pour sélectionner DateTime (DateTime, Datefield) + '/' + DateTime (mm, Datefield) + "/" + DateTime (aaaa, Datefi ELD) en tant que dateWithoutTime de l'Attaked_Total Limit 5. Est-ce correct? Merci encore pour votre réponse!


@Coomie, SQLite n'a pas de DatePart .


@Coomie, nous faisons tous des erreurs;)



31
votes

Vous pouvez utiliser Date Fonction.

Exemple P>

> select strftime('%d', '2011-04-26 18:40:34')
> 26


10 commentaires

erm oui je suis conscient de cette fonction. Cependant, je ne peux pas l'utiliser contre ma colosse qui s'appelle DateTime. Lorsque j'ai interrogé la date de sélection ('DateTime') de Tablename, une réponse vierge a été renvoyée. Merci pour votre réponse rapide ! :)


@user, ne pas mettre DateTime à l'intérieur des citations. Essayez date (DateTime)


ERM, toujours une réponse vierge est retournée.


@user, voudriez-vous poster la requête exacte?


Ok ici ça va! Nom: attaqué_total, colonne: DateTime Query: Sélectionnez la date (DateTime) à partir d'attaqués_total;


précisément ~. Sinon, je n'aurais pas eu d'affichage ici: d. merci quand même pour votre aide jusqu'à présent :)


@user, il serait préférable de modifier votre question pour refléter cette situation.


Je ne vois pas comment cela répond à la question de l'utilisateur, ça ne marche pas?


Merci. Cela a été utile dans l'effondrement des points de données par minute, par ex., Sélectionnez Strftime ('% Y% M% D% H% M', '2017-02-27T01: 30: 02') Time ... groupe par heure; # 201702270130


Ça marche, mais j'ai besoin d'enregistrements pour cette même contrainte qui devrait correspondre à une colonne particulière (dus_date) que j'ai créé_date et la date modifiée, je veux simplement obtenir des enregistrements correspondant à la date d'aujourd'hui à partir de la colonne Dompt_Date (qui est de type horodatage), comment atteindre cet?



1
votes

Ceci fonctionne.

SELECT strftime('%d', '2011-04-26')


0 commentaires

0
votes

Essayez d'utiliser ces fonctions si vous utilisez SQLite

Strftime ('% Y', Current_Date) P>

Strftime ('% m', courant_date) p>

Strftime ( '% d', courant_date) p>

droite ('% h', courant_date) p>

filtime ('% m', courant_date) p>

Strftime ('% S ', courant_date) p>

Si vous utilisez Hibernate, essayez d'enregistrer ces fonctions dans la classe SQLITITEDIALECT P>

import java.sql.SQLException;
import java.sql.Types;

import org.hibernate.JDBCException;
import org.hibernate.ScrollMode;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.function.AbstractAnsiTrimEmulationFunction;
import org.hibernate.dialect.function.NoArgSQLFunction;
import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.dialect.identity.IdentityColumnSupport;
import utiles.SQLiteDialectIdentityColumnSupport;
import org.hibernate.dialect.pagination.AbstractLimitHandler;
import org.hibernate.dialect.pagination.LimitHandler;
import org.hibernate.dialect.pagination.LimitHelper;
import org.hibernate.dialect.unique.DefaultUniqueDelegate;
import org.hibernate.dialect.unique.UniqueDelegate;
import org.hibernate.engine.spi.RowSelection;
import org.hibernate.exception.DataException;
import org.hibernate.exception.JDBCConnectionException;
import org.hibernate.exception.LockAcquisitionException;
import org.hibernate.exception.spi.SQLExceptionConversionDelegate;
import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter;
import org.hibernate.exception.spi.ViolatedConstraintNameExtracter;
import org.hibernate.internal.util.JdbcExceptionHelper;
import org.hibernate.mapping.Column;
import org.hibernate.type.StandardBasicTypes;

/**
 * An SQL dialect for SQLite 3.
 */
public class SQLiteDialect5 extends Dialect {

    private final UniqueDelegate uniqueDelegate;

    public SQLiteDialect5() {
        registerColumnType(Types.BIT, "boolean");
        //registerColumnType(Types.FLOAT, "float");
        //registerColumnType(Types.DOUBLE, "double");
        registerColumnType(Types.DECIMAL, "decimal");
        registerColumnType(Types.CHAR, "char");
        registerColumnType(Types.LONGVARCHAR, "longvarchar");
        registerColumnType(Types.TIMESTAMP, "datetime");
        registerColumnType(Types.BINARY, "blob");
        registerColumnType(Types.VARBINARY, "blob");
        registerColumnType(Types.LONGVARBINARY, "blob");

        registerFunction("concat", new VarArgsSQLFunction(StandardBasicTypes.STRING, "", "||", ""));
        registerFunction("mod", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "?1 % ?2"));
        registerFunction("quote", new StandardSQLFunction("quote", StandardBasicTypes.STRING));
        registerFunction("random", new NoArgSQLFunction("random", StandardBasicTypes.INTEGER));
        registerFunction("round", new StandardSQLFunction("round"));
        registerFunction("substr", new StandardSQLFunction("substr", StandardBasicTypes.STRING));
        registerFunction("year", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "abs(strftime('%Y', ?1))"));
        registerFunction("month", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "abs(strftime(strftime('%m', ?1))"));
        registerFunction("day", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "abs(strftime(strftime('%d', ?1))"));
        registerFunction("hour", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "abs(strftime(strftime('%H', ?1))"));
        registerFunction("minute", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "abs(strftime(strftime('%M', ?1))"));
        registerFunction("second", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "abs(strftime(strftime('%S', ?1))"));
        registerFunction("trim", new AbstractAnsiTrimEmulationFunction() {
            @Override
            protected SQLFunction resolveBothSpaceTrimFunction() {
                return new SQLFunctionTemplate(StandardBasicTypes.STRING, "trim(?1)");
            }

            @Override
            protected SQLFunction resolveBothSpaceTrimFromFunction() {
                return new SQLFunctionTemplate(StandardBasicTypes.STRING, "trim(?2)");
            }

            @Override
            protected SQLFunction resolveLeadingSpaceTrimFunction() {
                return new SQLFunctionTemplate(StandardBasicTypes.STRING, "ltrim(?1)");
            }

            @Override
            protected SQLFunction resolveTrailingSpaceTrimFunction() {
                return new SQLFunctionTemplate(StandardBasicTypes.STRING, "rtrim(?1)");
            }

            @Override
            protected SQLFunction resolveBothTrimFunction() {
                return new SQLFunctionTemplate(StandardBasicTypes.STRING, "trim(?1, ?2)");
            }

            @Override
            protected SQLFunction resolveLeadingTrimFunction() {
                return new SQLFunctionTemplate(StandardBasicTypes.STRING, "ltrim(?1, ?2)");
            }

            @Override
            protected SQLFunction resolveTrailingTrimFunction() {
                return new SQLFunctionTemplate(StandardBasicTypes.STRING, "rtrim(?1, ?2)");
            }
        });
        uniqueDelegate = new SQLiteUniqueDelegate(this);
    }

    // database type mapping support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    @Override
    public String getCastTypeName(int code) {
        // FIXME
        return super.getCastTypeName(code);
    }

    // IDENTITY support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    private static final SQLiteDialectIdentityColumnSupport IDENTITY_COLUMN_SUPPORT = new SQLiteDialectIdentityColumnSupport();

    @Override
    public IdentityColumnSupport getIdentityColumnSupport() {
        return IDENTITY_COLUMN_SUPPORT;
    }

    // limit/offset support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    private static final AbstractLimitHandler LIMIT_HANDLER = new AbstractLimitHandler() {
        @Override
        public String processSql(String sql, RowSelection selection) {
            final boolean hasOffset = LimitHelper.hasFirstRow(selection);
            return sql + (hasOffset ? " limit ? offset ?" : " limit ?");
        }

        @Override
        public boolean supportsLimit() {
            return true;
        }

        @Override
        public boolean bindLimitParametersInReverseOrder() {
            return true;
        }
    };

    @Override
    public LimitHandler getLimitHandler() {
        return LIMIT_HANDLER;
    }

    // lock acquisition support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    @Override
    public boolean supportsLockTimeouts() {
        // may be http://sqlite.org/c3ref/db_mutex.html ?
        return false;
    }

    @Override
    public String getForUpdateString() {
        return "";
    }

    @Override
    public boolean supportsOuterJoinForUpdate() {
        return false;
    }

    /*
    @Override
  public boolean dropTemporaryTableAfterUse() {
    return true; // temporary tables are only dropped when the connection is closed. If the connection is pooled...
  }
     */
    // current timestamp support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    @Override
    public boolean supportsCurrentTimestampSelection() {
        return true;
    }

    @Override
    public boolean isCurrentTimestampSelectStringCallable() {
        return false;
    }

    @Override
    public String getCurrentTimestampSelectString() {
        return "select current_timestamp";
    }

    // SQLException support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    private static final int SQLITE_BUSY = 5;

    private static final int SQLITE_LOCKED = 6;

    private static final int SQLITE_IOERR = 10;

    private static final int SQLITE_CORRUPT = 11;

    private static final int SQLITE_NOTFOUND = 12;

    private static final int SQLITE_FULL = 13;

    private static final int SQLITE_CANTOPEN = 14;

    private static final int SQLITE_PROTOCOL = 15;

    private static final int SQLITE_TOOBIG = 18;

    private static final int SQLITE_CONSTRAINT = 19;

    private static final int SQLITE_MISMATCH = 20;

    private static final int SQLITE_NOTADB = 26;

    @Override
    public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() {
        return new SQLExceptionConversionDelegate() {
            @Override
            public JDBCException convert(SQLException sqlException, String message, String sql) {
                final int errorCode = JdbcExceptionHelper.extractErrorCode(sqlException);
                if (errorCode == SQLITE_TOOBIG || errorCode == SQLITE_MISMATCH) {
                    return new DataException(message, sqlException, sql);
                } else if (errorCode == SQLITE_BUSY || errorCode == SQLITE_LOCKED) {
                    return new LockAcquisitionException(message, sqlException, sql);
                } else if ((errorCode >= SQLITE_IOERR && errorCode <= SQLITE_PROTOCOL) || errorCode == SQLITE_NOTADB) {
                    return new JDBCConnectionException(message, sqlException, sql);
                }

                // returning null allows other delegates to operate
                return null;
            }
        };
    }

    @Override
    public ViolatedConstraintNameExtracter getViolatedConstraintNameExtracter() {
        return EXTRACTER;
    }

    private static final ViolatedConstraintNameExtracter EXTRACTER = new TemplatedViolatedConstraintNameExtracter() {
        @Override
        protected String doExtractConstraintName(SQLException sqle) throws NumberFormatException {
            final int errorCode = JdbcExceptionHelper.extractErrorCode(sqle);
            if (errorCode == SQLITE_CONSTRAINT) {
                return extractUsingTemplate("constraint ", " failed", sqle.getMessage());
            }
            return null;
        }
    };

    // union subclass support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    @Override
    public boolean supportsUnionAll() {
        return true;
    }

    // DDL support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    @Override
    public boolean canCreateSchema() {
        return false;
    }

    @Override
    public boolean hasAlterTable() {
        // As specified in NHibernate dialect
        return false;
    }

    @Override
    public boolean dropConstraints() {
        return false;
    }

    @Override
    public boolean qualifyIndexName() {
        return false;
    }

    @Override
    public String getAddColumnString() {
        return "add column";
    }

    @Override
    public String getDropForeignKeyString() {
        throw new UnsupportedOperationException("No drop foreign key syntax supported by SQLiteDialect");
    }

    @Override
    public String getAddForeignKeyConstraintString(String constraintName,
            String[] foreignKey, String referencedTable, String[] primaryKey,
            boolean referencesPrimaryKey) {
        throw new UnsupportedOperationException("No add foreign key syntax supported by SQLiteDialect");
    }

    @Override
    public String getAddPrimaryKeyConstraintString(String constraintName) {
        throw new UnsupportedOperationException("No add primary key syntax supported by SQLiteDialect");
    }

    @Override
    public boolean supportsCommentOn() {
        return true;
    }

    @Override
    public boolean supportsIfExistsBeforeTableName() {
        return true;
    }

    /* not case insensitive for unicode characters by default (ICU extension needed)
    public boolean supportsCaseInsensitiveLike() {
    return true;
  }
     */
    @Override
    public boolean doesReadCommittedCauseWritersToBlockReaders() {
        // TODO Validate (WAL mode...)
        return true;
    }

    @Override
    public boolean doesRepeatableReadCauseReadersToBlockWriters() {
        return true;
    }

    @Override
    public boolean supportsTupleDistinctCounts() {
        return false;
    }

    @Override
    public int getInExpressionCountLimit() {
        // Compile/runtime time option: http://sqlite.org/limits.html#max_variable_number
        return 1000;
    }

    @Override
    public UniqueDelegate getUniqueDelegate() {
        return uniqueDelegate;
    }

    private static class SQLiteUniqueDelegate extends DefaultUniqueDelegate {

        public SQLiteUniqueDelegate(Dialect dialect) {
            super(dialect);
        }

        @Override
        public String getColumnDefinitionUniquenessFragment(Column column) {
            return " unique";
        }
    }

    @Override
    public String getSelectGUIDString() {
        return "select hex(randomblob(16))";
    }

    @Override
    public ScrollMode defaultScrollMode() {
        return ScrollMode.FORWARD_ONLY;
    }
}


0 commentaires