Acct BillingDate REV
101 01/05/2018 5
101 01/30/2018 4
102 01/15/2018 2
103 01/4/2018 3
103 02/05/2018 2
106 03/06/2018 5
Acct BillingDate Lease_Rev
101 01/15/2018 2
102 01/16/2018 1
103 01/19/2018 2
104 02/05/2018 3
105 04/02/2018 1
Acct Jan Feb Mar Apr
101 11
102 3
103 5 2
104 3
105 1
106 5
SELECT [NewSalesHistory].[Region]
,[NewSalesHistory].[Account]
,SUM(case when [NewSalesHistory].[billingdate] between '6/1/2016' and '6/30/2016' then REV else 0 end ) + [X].[Jun-16] AS 'Jun-16'
FROM [NewSalesHistory]
FULL join (SELECT [Account]
,SUM(case when [BWLease].[billingdate] between '6/1/2016' and '6/30/2016' then Lease_REV else 0 end ) as 'Jun-16'
FROM [AirgasPricing].[dbo].[BWLease]
GROUP BY [Account]) X ON [NewSalesHistory].[Account] = [X].[Account]
GROUP BY [NewSalesHistory].[Region]
,[NewSalesHistory].[Account]
,[X].[Jun-16]
我在合并这些表时遇到麻烦。如果有一个修订和租赁修订,则它将合并该帐户的(总和)。如果没有租用转帐(大多数时间),则表1中的所有其他转帐帐户都将带回NULL。表一可以有重复的帐户,但具有不同的转帐,而表二则是一个唯一帐户。仅w租赁转速。上面的输出是我希望看到的数据。
我在这里想念什么?谢谢!
答案 0 :(得分:0)
我建议使用 private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-F3KNAHJ;Initial Catalog=Login;Integrated Security=True");
string query = "Select * from Table Where username='" + textBox1.Text.Trim() + "' and password='" + textBox2.Text.Trim()+"'";
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
sda.Fill(dt);
if(dt.Rows.Count==1)
{
main objmain = new main();
this.Hide();
objmain.Show();
}
else
{
MessageBox.Show("Check your username or password");
}
和union all
:
group by
答案 1 :(得分:0)
好的,所以这里发生了一些事情:
1)正如Gordon Linoff所提到的,您可以对两个表全部执行并集。确保限制您选择的列并适当地命名列:
select
x as consistentname1,
y as consistentname2,
z as consistentname3
from [NewSalesHistory]
union all
select
a as consistentname1,
b as consistentname2,
c as consistentname3
from [BWLease]
2)您所需的结果包含一个透视的月份列。在第一步中,根据并集结果生成所需粒度的列。 F.ex.个月:
concat(datepart(yy, Date_),'-',datename(mm,Date_)) as yyyyM
然后使用分组依据:
select sum(...) as desiredcolumnname
...
group by PK1, PK2, yyyyM
最后,PIVOT获得您的结果:https://docs.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-2017
3)如果要显示其他字段/列,则首先需要确定它们是度量(可以汇总)还是维。在达到本部分的目的之后,最好在后续问题中解决这个问题。
希望有帮助
顺便说一句,似乎您正在准备报告数据。使用GUI(例如MS Power Query)可以方便地执行这些转换。只要您的最终目标不是在数据库本身中进行数据操作,就不必求助于原始sql。