如何在Oracle select语句中声明变量

时间:2019-01-03 14:32:46

标签: sql oracle

我有这个Oracle SQL请求:

[INFO] Scanning for projects...
[INFO] 
[INFO] ---------------------------< theo.jpa:demo >----------------------------
[INFO] Building example 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ demo ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ demo ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ demo ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/theodosiostziomakas/Desktop/Java Spring Tutorials/spring-boot-spring-mvc-bootstrap/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ demo ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-surefire-plugin:2.22.1:test (default-test) @ demo ---
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running theo.jpa.demo.ExampleApplicationTests
17:24:41.733 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class theo.jpa.demo.ExampleApplicationTests]
17:24:41.742 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
17:24:41.756 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
17:24:41.787 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [theo.jpa.demo.ExampleApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
17:24:41.991 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [theo.jpa.demo.ExampleApplicationTests], using SpringBootContextLoader
17:24:42.007 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [theo.jpa.demo.ExampleApplicationTests]: class path resource [theo/jpa/demo/ExampleApplicationTests-context.xml] does not exist
17:24:42.011 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [theo.jpa.demo.ExampleApplicationTests]: class path resource [theo/jpa/demo/ExampleApplicationTestsContext.groovy] does not exist
17:24:42.011 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [theo.jpa.demo.ExampleApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
17:24:42.013 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [theo.jpa.demo.ExampleApplicationTests]: ExampleApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
17:24:42.135 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [theo.jpa.demo.ExampleApplicationTests]
17:24:42.349 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [/Users/theodosiostziomakas/Desktop/Java Spring Tutorials/spring-boot-spring-mvc-bootstrap/target/classes/theo/jpa/demo/ExampleApplication.class]
17:24:42.351 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration theo.jpa.demo.ExampleApplication for test class theo.jpa.demo.ExampleApplicationTests
17:24:42.600 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [theo.jpa.demo.ExampleApplicationTests]: using defaults.
17:24:42.603 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
17:24:42.742 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@692f203f, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@48f2bd5b, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@7b2bbc3, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@a1153bc, org.springframework.test.context.support.DirtiesContextTestExecutionListener@1aafa419, org.springframework.test.context.transaction.TransactionalTestExecutionListener@47eaca72, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@55141def, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@55182842, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@3270d194, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@235834f2, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@5656be13, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@4218d6a3]
17:24:42.758 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [theo.jpa.demo.ExampleApplicationTests]
17:24:42.760 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [theo.jpa.demo.ExampleApplicationTests]
17:24:42.762 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [theo.jpa.demo.ExampleApplicationTests]
17:24:42.767 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [theo.jpa.demo.ExampleApplicationTests]
17:24:42.787 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [theo.jpa.demo.ExampleApplicationTests]
17:24:42.788 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [theo.jpa.demo.ExampleApplicationTests]
17:24:42.862 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@4afcd809 testClass = ExampleApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@175c2241 testClass = ExampleApplicationTests, locations = '{}', classes = '{class theo.jpa.demo.ExampleApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@1fc2b765, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@22eeefeb, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@10a035a0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@31f924f5], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] with mode [null].
17:24:42.870 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [theo.jpa.demo.ExampleApplicationTests]
17:24:42.870 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [theo.jpa.demo.ExampleApplicationTests]
17:24:42.961 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=-1}

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.1.RELEASE)

2019-01-03 17:24:58.582  INFO 1289 --- [           main] theo.jpa.demo.ExampleApplicationTests    : Starting ExampleApplicationTests on Theodosioss-MacBook-Pro.local with PID 1289 (started by theodosiostziomakas in /Users/theodosiostziomakas/Desktop/Java Spring Tutorials/spring-boot-spring-mvc-bootstrap)
2019-01-03 17:24:58.584  INFO 1289 --- [           main] theo.jpa.demo.ExampleApplicationTests    : No active profile set, falling back to default profiles: default
2019-01-03 17:24:59.422  INFO 1289 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-01-03 17:24:59.475  INFO 1289 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 23ms. Found 0 repository interfaces.
2019-01-03 17:24:59.955  INFO 1289 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$819e6851] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-01-03 17:25:00.261  INFO 1289 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-01-03 17:25:00.841  INFO 1289 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-01-03 17:25:00.931  INFO 1289 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
        name: default
        ...]
2019-01-03 17:25:01.090  INFO 1289 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.7.Final}
2019-01-03 17:25:01.092  INFO 1289 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-01-03 17:25:01.346  INFO 1289 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-01-03 17:25:01.547  INFO 1289 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-01-03 17:25:01.884  INFO 1289 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-01-03 17:25:02.823  INFO 1289 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-01-03 17:25:02.903  WARN 1289 --- [           main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-01-03 17:25:03.305  INFO 1289 --- [           main] theo.jpa.demo.ExampleApplicationTests    : Started ExampleApplicationTests in 20.327 seconds (JVM running for 22.223)
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 21.899 s - in theo.jpa.demo.ExampleApplicationTests
2019-01-03 17:25:03.437  INFO 1289 --- [       Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2019-01-03 17:25:03.438  INFO 1289 --- [       Thread-2] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2019-01-03 17:25:03.440  INFO 1289 --- [       Thread-2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2019-01-03 17:25:03.478  INFO 1289 --- [       Thread-2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] 
[INFO] --- maven-jar-plugin:3.1.0:jar (default-jar) @ demo ---
[INFO] Building jar: /Users/theodosiostziomakas/Desktop/Java Spring Tutorials/spring-boot-spring-mvc-bootstrap/target/demo-0.0.1-SNAPSHOT.jar
[INFO] 
[INFO] --- spring-boot-maven-plugin:2.1.1.RELEASE:repackage (repackage) @ demo ---
[INFO] Replacing main artifact with repackaged archive
[INFO] 
[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ demo ---
[INFO] Installing /Users/theodosiostziomakas/Desktop/Java Spring Tutorials/spring-boot-spring-mvc-bootstrap/target/demo-0.0.1-SNAPSHOT.jar to /Users/theodosiostziomakas/.m2/repository/theo/jpa/demo/0.0.1-SNAPSHOT/demo-0.0.1-SNAPSHOT.jar
[INFO] Installing /Users/theodosiostziomakas/Desktop/Java Spring Tutorials/spring-boot-spring-mvc-bootstrap/pom.xml to /Users/theodosiostziomakas/.m2/repository/theo/jpa/demo/0.0.1-SNAPSHOT/demo-0.0.1-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 31.386 s
[INFO] Finished at: 2019-01-03T17:25:05+02:00
[INFO] ------------------------------------------------------------------------

我在问是否有一种方法可以声明一种变量并具有如下所示的内容:

SELECT col1,
       col2,
       DECODE(
                 SUM(CASE WHEN col3='A' AND col4='+' THEN col5 ELSE 0 END),
                 NULL,
                 0,
                 SUM(CASE WHEN col3='A' AND col4='+' THEN col5 ELSE 0 END)
             )
FROM mytable
group by col1, col2;

4 个答案:

答案 0 :(得分:1)

否,但是您可以执行子查询:

SELECT col1,
       col2,
       DECODE(
                 SUM(myColumn),
                 NULL,
                 0,
                 SUM(myColumn)
             )
FROM (
    SELECT 
        col1,
        col2,
        CASE WHEN col3='A' AND col4='+' THEN col5 ELSE 0 END myColumn   
        FROM mytable
     ) a
group by col1, col2;

答案 1 :(得分:0)

是的,您可以使用替换变量:

SELECT col1,
       col2,
       DECODE(
                 &&myVariable,
                 NULL,
                 0,
                 &&myVariable
             )
FROM mytable
group by col1, col2;

此处更多信息Oracle SQL*Plus Substitution Variables

答案 2 :(得分:0)

您可以简单地使用coalesce()(或nvl())代替decode()

SELECT col1,
       col2,
       coalesce(sum(CASE
                      WHEN col3 = 'A'
                           AND col4 = '+' THEN
                        col5
                      ELSE
                        0
                    END),
                0)
       FROM mytable
       GROUP BY col1,
                col2;

答案 3 :(得分:0)

您可以使用coalesce()。我认为这已经足够了:

select col1, col2,
       coalesce(sum(case when col3 = 'A' and col4 = '+' then col5 end), 0)
from mytable
group by col1, col2;

实际上,此表达式:

sum(case when col3 = 'A' and col4 = '+' then col5 else 0 end)

在带有NULL的查询中无法返回group by -每个组至少有一行,并且else保证返回0而不是{{1} }。

所以,这也应该做您想要的:

NULL