我有一张桌子,我想要a型的统计价格,输入c作为卖出,输入b,然后按日期输入d作为买入,结果如
Table :
| Name | type | price | day |
| n1 | a | 1 |2013-10-10 |
| n2 | b | 2 |2013-10-10 |
| n3 | c | 3 |2013-10-10 |
| n4 | d | 4 |2013-10-10 |
| n1 | a | 5 |2013-11-10 |
| n2 | b | 6 |2013-11-10 |
| n3 | c | 7 |2013-11-10 |
| n4 | d | 8 |2013-11-10 |
我想要这样的结果
| DAY | SELL (price a+price c) | BUY (price b +price d) |
|2013-10-10 | 4 | 6 |
|2013-11-10 | 12 | 14 |
这是我的代码
ALTER proc [dbo].[sp_mysp]
@starttime datetime,
@endtime datetime
as
DECLARE @TIME DATETIME
SET @TIME=@ENDTIME-@STARTTIME
SELECT (table.day) AS DAY , case BUY
WHEN TABLE.TYPE ='a' or TABLE.TYPE = 'c' THEN SUM (price) end,
CASE SELL
WHEN TABLE.TYPE = 'b' or TABLE.TYPE = 'd' THEN SUM (price) end,
FROM TABLE WHERE TABLE.DAY>@starttime AND TABLE.TIME<@ENDTIME
order by TABLE.DAY
GO
我不能总和(输入a和类型c),总和(类型b和类型d)如我所愿,它只能通过类型a与a,b和b相加...... 我得到的结果像
| DAY | SELL (price a+price c) | BUY (price b +price d) |
| 2013-10-10 | 1 | NULL |
| 2013-10-10 | 3 | NULL |
| 2013-10-10 | NULL | 2 |
| 2013-10-10 | NULL | 4 |
| 2013-11-10 | 5 | NULL |
| 2013-11-10 | 7 | NULL |
| 2013-11-10 | NULL | 6 |
| 2013-11-10 | NULL | 8 |
对我来说有什么意义吗?
对不起我可怕的英语。
答案 0 :(得分:1)
尝试
我没有在你的表中看到时间,但我猜DAY列是日期格式
ALTER proc [dbo].[sp_mysp]
@starttime datetime,
@endtime datetime
as
SELECT [Day],
SUM(CASE WHEN [Type] = 'a' OR [Type] = 'c' THEN price ELSE 0.00 END) SELL,
SUM(CASE WHEN [Type] = 'b' OR [Type] = 'd' THEN price ELSE 0.00 END) BUY
FROM [TABLE]
WHERE [Day] BETWEEN @starttime AND @endtime
GROUP BY [Day]
答案 1 :(得分:-2)
我认为你的
TABLE.TYPE ='a' or TABLE.TYPE = 'c'
应该是
TABLE.TYPE ='a' AND TABLE.TYPE = 'c'
这样,它只会归结为IF都是你需要的。