我想要执行一个Threshold查询,其中一个人将从Today获取一个字段的值,并将其与昨天的值进行比较,这个查询看起来像这样,但很明显,这是错误的,我找不到怎么做:
select
TableB.Name,
TableA.Charge,
(
select Charge
from TableA
where (DateAdded >= '13/10/2009' and DateAdded < '14/10/2009')
)
from TableA
inner join
TableB on TableB.ID = TableA.ID
where
TableA.DateAdded >= '10/14/2009'
order by
Name asc
请注意,我正在寻找两个CHARGE
字段,而不是日期。日期操作仅适用于今天和昨天,仅此而已。
最后,我想对两个返回的电荷字段进行计算,因此如果更容易显示,那也很棒。
提前致谢
凯尔
EDIT1:
我正在寻找的数据是这样的:
昨天,我们向MachineA收取500的费用 今天我们向MachineA
输入300的费用我们运行查询,我需要的结果如下:
Name = MachineA
Charge = 300
YesterdayCharge = 500
答案 0 :(得分:0)
SELECT
B.Name,
A.Charge,
DATEPART(day, A.DateAdded) as day
FROM
TableA A, Table B
WHERE
B.ID = A.ID AND
A.DateAdded BETWEEN DATEADD(day, -1, GETDATE()) AND GETDATE()
GROUP BY
B.Name,
A.Charge,
A.DateAdded
答案 1 :(得分:0)
试试这个:
DECLARE @ValuesTable TABLE(Name VARCHAR(20), Charge INT, DateAdded DATETIME)
INSERT INTO @ValuesTable
SELECT 'Name1', 10, DATEADD(dd, 2, DATEDIFF(dd, 0, GETDATE())) UNION
SELECT 'Name2', 20, DATEADD(dd, 2, DATEDIFF(dd, 0, GETDATE())) UNION
SELECT 'Name1', 30, DATEADD(dd, 1, DATEDIFF(dd, 0, GETDATE())) UNION
SELECT 'Name2', 40, DATEADD(dd, 1, DATEDIFF(dd, 0, GETDATE())) UNION
SELECT 'Name1', 50, DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())) UNION
SELECT 'Name2', 60, DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())) UNION
SELECT 'Name1', 70, DATEADD(dd, -1, DATEDIFF(dd, 0, GETDATE())) UNION
SELECT 'Name3', 80, DATEADD(dd, -1, DATEDIFF(dd, 0, GETDATE())) UNION
SELECT 'Name1', 90, DATEADD(dd, -2, DATEDIFF(dd, 0, GETDATE())) UNION
SELECT 'Name2', 100, DATEADD(dd, -2, DATEDIFF(dd, 0, GETDATE()))
SELECT
ISNULL(T.Name,Y.Name) AS Name,
SUM(ISNULL(Y.Charge,0)) AS Yesterday, SUM(ISNULL(T.Charge,0)) AS Today,
SUM(ISNULL(T.Charge,0)) - SUM(ISNULL(Y.Charge,0)) AS Diff
FROM(
SELECT Name, Charge
FROM @ValuesTable
WHERE DateAdded BETWEEN DATEADD(day, -2, GETDATE())
AND DATEADD(day, -1, GETDATE())
) AS Y
FULL JOIN(
SELECT Name, Charge
FROM @ValuesTable
WHERE DateAdded BETWEEN DATEADD(day, -1, GETDATE()) AND GETDATE()
) AS T ON ISNULL(T.Name,Y.Name) = ISNULL(Y.Name,T.Name)
GROUP BY ISNULL(T.Name,Y.Name) , ISNULL(Y.Name,T.Name)
答案 2 :(得分:0)
如果您确实需要上一个日期(包括周末等),那么以下查询应该完成这项工作。否则,请发布数据样本和预期结果:
SELECT TableB.Name,
TableA.Charge,
prev.Charge AS PrevCharge
FROM TableA
INNER JOIN TableB
ON TableA.ID = TableB.ID
LEFT JOIN TableA prev
ON TableA.ID = prev.ID
--// use this if DateAdded contains only date
--AND TableA.DateAdded = DATEADD(day, +1, prev.dateAdded)
--// use this if DateAdded contains also time component
AND CONVERT(DATETIME, CONVERT(CHAR(8), TableA.DateAdded, 112), 112) = DATEADD(day, +1, CONVERT(DATETIME, CONVERT(CHAR(8), prev.dateAdded, 112), 112))
edit-1:在JOIN中添加了选项
答案 3 :(得分:0)
在SO中可能只是一个拼写错误,但如果您在同一查询中使用日期字符串'14 / 10/2009'和'10 / 14/2009',它将无法正常工作。 无论您使用哪种日期格式,其中一种格式都有太长的月份。