我试图在存储过程中做一个很好的SQL语句.
我查看了查看两个日期之间发生事件的天数的问题.我的例子是销售订单:本月,我们有多少天销售订单?
假设这个设置:
CREATE TABLE `sandbox`.`orders` ( `year` int, `month` int, `day` int, `desc` varchar(255) ) INSERT INTO orders (year, month, day, desc) VALUES (2009,1,1, 'New Years Resolution 1') ,(2009,1,1, 'Promise lose weight') ,(2009,1,2, 'Bagel') ,(2009,1,12, 'Coffee to go')
对于这个数据中的结果应该是3,因为已经有三天的销售.我找到的最佳解决方案如下.
然而,制作一个临时表,计算然后丢失它似乎过多.它应该在一个声明中"成为可能".
任何得到"更好"解决方案的人呢?
/ L
SELECT [Year], [Month], [Day] INTO #Some_Days FROM Quarter WHERE Start >= '2009-01-01' AND [End] < '2009-01-16' GROUP BY [Year], [Month], [Day] SELECT count(*) from #Some_Days
Christian Nu.. 9
如果我误解了这个问题,请道歉,但也许你可以这样做,作为一个选择:
SELECT COUNT(*) FROM (SELECT DISTINCT(SomeColumn) FROM MyTable WHERE Something BETWEEN 100 AND 500 GROUP BY SomeColumn) MyTable
...绕过临时表的创建和处理?
如果我误解了这个问题,请道歉,但也许你可以这样做,作为一个选择:
SELECT COUNT(*) FROM (SELECT DISTINCT(SomeColumn) FROM MyTable WHERE Something BETWEEN 100 AND 500 GROUP BY SomeColumn) MyTable
...绕过临时表的创建和处理?