如何在一个查询中做到这一点

时间:2019-01-30 15:53:20

标签: sql sql-server sql-server-2012

我正在尝试在一个查询中编写此代码。我该怎么办?

基本上我每个月都需要这个,所以我不能写30次。任何可能的实现方式请分享。 在下面的查询中,相同的代码被写入3次,但日期参数不同。

Select  
case when Cast(ILE.[Posting Date] as date) <  Cast(Getdate() as date)  then cast(ILE.Quantity as Numeric(19,6)) else 0 end AS [Opening],
case when Cast(ILE.[Posting Date] as date) <=  Cast(Getdate() as date)  then cast(ILE.Quantity as Numeric(19,6)) else 0 end AS [Closing]
from  [Item Ledger Entry] ILE
where Cast(ILE.[Posting Date] as date) <= Cast(Getdate() as date)

Union all

Select  
case when Cast(ILE.[Posting Date] as date) <  Cast(Getdate()-1 as date)  then cast(ILE.Quantity as Numeric(19,6)) else 0 end AS [Opening],
case when Cast(ILE.[Posting Date] as date) <=  Cast(Getdate()-1 as date)  then cast(ILE.Quantity as Numeric(19,6)) else 0 end AS [Closing]
from [Item Ledger Entry] ILE
where Cast(ILE.[Posting Date] as date) <= Cast(Getdate()-1 as date)

union all

Select  
case when Cast(ILE.[Posting Date] as date) <  Cast(Getdate()-2 as date)  then cast(ILE.Quantity as Numeric(19,6)) else 0 end AS [Opening],
case when Cast(ILE.[Posting Date] as date) <=  Cast(Getdate()-2 as date)  then cast(ILE.Quantity as Numeric(19,6)) else 0 end AS [Closing]
from [Item Ledger Entry] ILE
where Cast(ILE.[Posting Date] as date) <= Cast(Getdate()-2 as date)

通过使用上面的查询,数据将如下图所示。  https://i.stack.imgur.com/Hc6Co.png

2 个答案:

答案 0 :(得分:0)

为什么不使用CONVERT(VARCHAR(7),ILE。[Posting Date],120)来在该月份中按此分组,如果您需要按天,则将varchar(7)更改为varchar(10)。删除并集,然后编写一个基本的聚合查询。

注意: :您也可以在分组的选择部分中使用此选项,并且要细分的字段可以为您提供正确的细分。

此时和您的范围逻辑也必须更改的情况。

答案 1 :(得分:0)

尝试一下:

csvfile = open('file.csv','r')
jsonfile = open('file.json','w')

reader = csv.DictReader(csvfile)
jsonfile.write('[')

for row in reader:
    json.dump(row, jsonfile)
    jsonfile.write(',')
    jsonfile.write('\n')
jsonfile.write(']')