由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Database版 - SQL Conditional Select
相关主题
MS T-SQL 问题Access门外汉问题求教
[转载] Can anyone interpret this simple SQL?请教2个sql query 问题
Merge table with one single query?correlated subquery
问一个SQL Server的问题About INSERT IGNORE
请教大牛一道有趣的SQL题Question about SQL server lock
Problem when using SQL " Insert...." to AutoNumber.SQL Server set implicit_transaction on
SQL fast search in a 10 million records table (转载)谁给我优化一下把重复的产品下架的SQL
今典问题: 这个Self Query咋写?SQL 请教
相关话题的讨论汇总
话题: inv话题: cr话题: 1234话题: sales话题: select
进入Database版参与讨论
1 (共1页)
i****a
发帖数: 36252
1
SQL 2005, Have the following data
seq ID month type amount
1 1234 1 R 421
2 1234 1 Cr 410
3 1234 1 Inv 430
1 1234 2 Cr 625
2 1234 2 Inv 650
1 1234 3 Inv 916
1 1234 4 Inv 882
How to get the rows of Inv and Cr, only when Cr exists for that month, and
the difference between Cr and Inv
example result:
1234, 1, Cr, 410
1234, 1, Inv, 430, difference 20
1234, 2, Cr, 625
1234, 2, Inv, 650, difference 25
i****a
发帖数: 36252
2
found this example. can do calculation from the sub query
CREATE TABLE Sales (DayCount smallint, Sales money)
CREATE CLUSTERED INDEX ndx_DayCount ON Sales(DayCount)
go
INSERT Sales VALUES (1,120)
INSERT Sales VALUES (2,60)
INSERT Sales VALUES (3,125)
INSERT Sales VALUES (4,40)
select *
from Sales
SELECT DayCount,
Sales,
coalesce((SELECT Sales
FROM Sales b
WHERE b.DayCount = a.DayCount+1), 0)
AS NextDaySales
FROM S
s*******6
发帖数: 3
3
select k.ID,k.mon,k.type,k.amount,
( select case k.amount-amount
when 0 then NULL
else k.amount-amount
end

from table where ID=k.id and MON=k.mon and TYPE='CR') as difference
from table as k,
(select ID,MON,COUNT (*) as test from table
where TYPE='Cr' or TYPE='Inv'
group by ID,MON having COUNT(*)>1) as s
where k.id=s.id
and k.mon=s.mon
and (k.TYPE='Cr' or k.TYPE='Inv')
i****a
发帖数: 36252
4
thanks!
I followed the example on 2nd post and got the result.

【在 s*******6 的大作中提到】
: select k.ID,k.mon,k.type,k.amount,
: ( select case k.amount-amount
: when 0 then NULL
: else k.amount-amount
: end
:
: from table where ID=k.id and MON=k.mon and TYPE='CR') as difference
: from table as k,
: (select ID,MON,COUNT (*) as test from table
: where TYPE='Cr' or TYPE='Inv'

1 (共1页)
进入Database版参与讨论
相关主题
SQL 请教请教大牛一道有趣的SQL题
再现急求答案,多谢。Problem when using SQL " Insert...." to AutoNumber.
sql的2个问题 (转载)SQL fast search in a 10 million records table (转载)
谁能帮我看看这个Insert语句要怎么改一下?今典问题: 这个Self Query咋写?
MS T-SQL 问题Access门外汉问题求教
[转载] Can anyone interpret this simple SQL?请教2个sql query 问题
Merge table with one single query?correlated subquery
问一个SQL Server的问题About INSERT IGNORE
相关话题的讨论汇总
话题: inv话题: cr话题: 1234话题: sales话题: select