我不确定在where子句中给出这个条件的正确名称是什么。我正在使用Microsoft SQL Server 2008。
基本上,我有一个包含以下列的订单表。
MyOrderTable:
OrderAmount Paid OrderDate
100 Y 2016-08-10 21:15:52.000
120 N 2016-08-10 20:15:12.000
300 Y 2016-08-09 11:10:22.000
500 Y 2016-06-09 10:10:54.000
125 N 2016-06-09 09:15:13.000
325 N 2015-11-09 09:15:13.000
目前,我有以下SQL查询:
SELECT DATEPART(Year, OrderDate) TheYear, DATEPART(Month, OrderDate) TheMonth,
SUM(ISNULL(OrderAmount, 0)) as SumOrderAmount
FROM MyOrderTable
WHERE YEAR(OrderDate) = 2016
GROUP BY DATEPART(Year, OrderDate), DATEPART(Month, OrderDate)
ORDER BY TheYear, TheMonth
从上面的SQL返回的结果如下:
TheYear TheMonth SumOrderAmount
2016 6 625
2016 8 520
如何查询SumOrderAmount,其中行是Paid =' Y'?我想从SQL中返回以下内容:
TheYear TheMonth SumOrderAmount PaidSumOrderAmount
2016 6 625 500
2016 8 520 400
我该怎么做?任何帮助是极大的赞赏。谢谢。
答案 0 :(得分:1)
使用case
表达式执行条件SUM()
:
SELECT DATEPART(Year, OrderDate) TheYear, DATEPART(Month, OrderDate) TheMonth,
SUM(ISNULL(OrderAmount, 0)) as SumOrderAmount,
SUM(case when Paid='Y' then OrderAmount end)
FROM MyOrderTable
WHERE YEAR(OrderDate) = 2016
GROUP BY DATEPART(Year, OrderDate), DATEPART(Month, OrderDate)
ORDER BY TheYear, TheMonth
答案 1 :(得分:1)
使用条件聚合:
10-08 14:15:59 DEBUG JpaTransactionManager - Creating new transaction with name [es.package.app.repository.jpa.JPAValorMaximo.update]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
10-08 14:15:59 DEBUG JpaTransactionManager - Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl@405264e8] for JPA transaction
10-08 14:15:59 DEBUG AbstractTransactionImpl - begin
10-08 14:15:59 DEBUG LogicalConnectionImpl - Obtaining JDBC connection
10-08 14:15:59 DEBUG LogicalConnectionImpl - Obtained JDBC connection
10-08 14:15:59 DEBUG JdbcTransaction - initial autocommit status: true
10-08 14:15:59 DEBUG JdbcTransaction - disabling autocommit
10-08 14:15:59 DEBUG JpaTransactionManager - Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@1bbb3b9e]
10-08 14:15:59 DEBUG SQL - UPDATE table SET field= LEAST(NUMERADOR/DENOMINADO, ? )
Hibernate: UPDATE table SET field= LEAST(NUMERADOR/DENOMINADO, ? )
您可能不需要SELECT DATEPART(Year, OrderDate) TheYear, DATEPART(Month, OrderDate) TheMonth,
SUM(ISNULL(OrderAmount, 0)) as SumOrderAmount,
SUM(CASE WHEN Paid = 'Y' THEN OrderAmount ELSE 0 END) as PaidOrderAmount
FROM MyOrderTable
WHERE YEAR(OrderDate) = 2016
GROUP BY DATEPART(Year, OrderDate), DATEPART(Month, OrderDate)
ORDER BY TheYear, TheMonth;
中的ISNULL()
。在SQL中,SUM()
聚合函数中会忽略NULL
个值。
答案 2 :(得分:0)
在select:
上添加此子句${MyVersion}
答案 3 :(得分:0)
SELECT DATEPART(Year, OrderDate) TheYear, DATEPART(Month, OrderDate) TheMonth,
SUM(ISNULL(OrderAmount, 0)) as SumOrderAmount,Paid
FROM MyOrderTable
WHERE (YEAR(OrderDate) = 2016) and (Paid = 'Y')
GROUP BY DATEPART(Year, OrderDate), DATEPART(Month, OrderDate)
ORDER BY TheYear, TheMonth