我正在尝试建立多个子查询查询,以便可以将结果数据绑定到图表

这是我当前的查询:

SELECT TOP (100) PERCENT Sum(DBO.ORDERLINE.QTY)               AS UnitsSold,
                         { fn HOUR(dbo.[Order].PaymentDate) } AS MyHour
FROM   DBO.[ORDER]
       INNER JOIN DBO.ORDERLINE
               ON DBO.[ORDER].ORDERID = DBO.ORDERLINE.ORDERID
WHERE  ( DBO.[ORDER].WEBSITEID = 2 )
       AND ( DBO.[ORDER].ORDERSTATUSID = 2 )
       AND ( Day(DBO.[ORDER].PAYMENTDATE) = 01 )
       AND ( Month(DBO.[ORDER].PAYMENTDATE) = 08 )
       AND ( Year(DBO.[ORDER].PAYMENTDATE) = 2013 )
GROUP  BY { fn HOUR(dbo.[Order].PaymentDate) }


这将根据昨天的数据返回两列,即UnitsSold和MyHour-效果很好。

但是我也想在上周的同一天和去年的同一天获得相同的数据,我自己可以通过c#提供MONTH / DAY / YEAR值-我只是不确定如何执行这个复杂的查询。

让我知道您是否需要更多信息。

谢谢,

麦可

最佳答案

如果我正确理解您的问题,则只需要一个查询即可获得3个结果。

您可以使用union all

这会将3个查询与不同的日期间隔组合在一起。
您将获得一个包含3行的结果集。

更新

您可以合并这样的查询(未经测试,不在我的电脑上)

SELECT TOP (100) PERCENT Sum(DBO.ORDERLINE.QTY) AS UnitsSold, { fn HOUR(dbo.[Order].PaymentDate) } AS MyHour
FROM   DBO.[ORDER]
       INNER JOIN DBO.ORDERLINE
               ON DBO.[ORDER].ORDERID = DBO.ORDERLINE.ORDERID
WHERE  ( DBO.[ORDER].WEBSITEID = 2 )
       AND ( DBO.[ORDER].ORDERSTATUSID = 2 )
       AND ( Day(DBO.[ORDER].PAYMENTDATE) = 01 )
       AND ( Month(DBO.[ORDER].PAYMENTDATE) = 08 )
       AND ( Year(DBO.[ORDER].PAYMENTDATE) = 2013 )
GROUP  BY { fn HOUR(dbo.[Order].PaymentDate) }

union all

SELECT TOP (100) PERCENT Sum(DBO.ORDERLINE.QTY) AS UnitsSold, { fn HOUR(dbo.[Order].PaymentDate) } AS MyHour
FROM   DBO.[ORDER]
       INNER JOIN DBO.ORDERLINE
               ON DBO.[ORDER].ORDERID = DBO.ORDERLINE.ORDERID
WHERE  ( DBO.[ORDER].WEBSITEID = 2 )
       AND ( DBO.[ORDER].ORDERSTATUSID = 2 )
       AND ( Day(DBO.[ORDER].PAYMENTDATE) = 24 )
       AND ( Month(DBO.[ORDER].PAYMENTDATE) = 07 )
       AND ( Year(DBO.[ORDER].PAYMENTDATE) = 2013 )
GROUP  BY { fn HOUR(dbo.[Order].PaymentDate) }

union all

SELECT TOP (100) PERCENT Sum(DBO.ORDERLINE.QTY) AS UnitsSold, { fn HOUR(dbo.[Order].PaymentDate) } AS MyHour
FROM   DBO.[ORDER]
       INNER JOIN DBO.ORDERLINE
               ON DBO.[ORDER].ORDERID = DBO.ORDERLINE.ORDERID
WHERE  ( DBO.[ORDER].WEBSITEID = 2 )
       AND ( DBO.[ORDER].ORDERSTATUSID = 2 )
       AND ( Day(DBO.[ORDER].PAYMENTDATE) = 01 )
       AND ( Month(DBO.[ORDER].PAYMENTDATE) = 08 )
       AND ( Year(DBO.[ORDER].PAYMENTDATE) = 2012 )
GROUP  BY { fn HOUR(dbo.[Order].PaymentDate) }


您的数据将获得3行。如果需要,您还可以添加一个伪造的列,说明该图表的当前日期(今天,上周,去年)

关于c# - 获取今天,上周同一天和去年同一天售出的商品,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18021110/

10-10 23:08