Iqueryable Group By Multiple Columns

Let's start by revisiting our IQueryable skeleton implementation. Net library in c#, vb. For example, the search feature in this application allows the user to find all records that meet criteria defined on multiple columns:. This allowed me to name the results of the group by operation so I could continue to operate on the group (singular) further down the line (via order by). I know what you're thinking, "Why in the world would they retrieve more columns than they need?" Well, because it's easy. In addition, the DataSet also exposes a number of services (i. Re: Joins and Left Outer Joins in LINQ-Do you want groups with that? This site is excellent and so is how the subject matter was explained. [Grid - ASP. Personally I think this is a good thing. He is also fond of crazy column names. For background on EF, see my previous article, "Introducing ADO. Contains("a"). The challenge with the above chart is that the “Drivers” (i. Group By SalesDateTime; Finally, a few notes on missing data possibility. How to: Convert the Results of a LINQ Query to an Array. There is one row in the table for each column returned in the reader, and the columns of the schema table define properties of the reader’s result set, such as the column name, size, data type and so on. This query will select all documents in the inventory collection where:. I also like some of the comments too. A few times recently when I've been creating a view for full text indexing on Sql Server, I've had need to return the results of a one to many relationship in one row. This group is contained in a special type of collection that implements an IGrouping interface where TKey is a key value, on which the group has been formed and TSource is the collection of elements that matches with the grouping key value. Data; using System. Like it or not, LINQ is here to stay. I want to create a linq dynamic query using group by and aggregate function like sum on different column of same table. C# (CSharp) IQueryable. NET › Retrieving data with DbContext. except when a content item is assigned to multiple roles. In application we can able to working with object easily with writing quires. The generated array or list is a snapshot taken at the moment the query is run. 1) doesn’t support returning arrays, lists etc from explicitly compiled queries. Recent Posts Authors. GroupBy operator belong to Grouping Operators category. LINQ provides the default (and the most common) implementation of both of the operations, but sometimes you may need a slightly different behavior when grouping or ordering data (this article is motivated by a question on. So, you wouldn’t be using a repository in this class. You can apply an additional order-by after the group-by to order the groups specificly. The primary difference between both the classes is that an. By a compound key. This operator takes a flat sequence of items, organize that sequence into groups (IGrouping[K,V]) based on a specific key and return groups. ProjectTo() will tell AutoMapper's mapping engine to emit a select clause to the IQueryable that will inform entity framework that it only needs to query the Name column of the Item table, same as if you manually projected your IQueryable to an OrderLineDTO with a Select clause. Provides a set of static methods for querying data structures that implement IQueryable. Since the first beta versions of LINQ we could hear comments that it is perfect for queries known at compile-time, however it is not possible to use it for building queries dynamically at runtime. The following query works fine when I know that I want to group by "Dim1" and "Dim2". Hi! I'm working on group by queries on sqlserver. Each one is designed to tolerate particular architecture principles. In this tip, I show you how to create a custom action result that you can return from an ASP. Update: October 26, 2016 - I would now recomend using this replacement guide using the built in PetaPoco instead of this method as it is much cleaner and requires significantly less DBA code and produced much smaller binaries. I want to query my IQueryable list of Invoices and group by Structure. The scenario you’re talking about is for reporting. except when a content item is assigned to multiple roles. Only members identified as columns are persisted when LINQ to SQL saves changes to the database. Question How can I do GroupBy Multiple Columns in LINQ Something similar to this in SQL: SELECT * FROM GROUP BY , How can I convert this to LINQ: QuantityBreakdown ( MaterialID INT, ProductID INT, Quantity FLOAT ) INSERT INTO @QuantityBreakdown (MaterialID, ProductID, Quantity) SELECT MaterialID, ProductID, SUM. How Do I Read XML using LINQ to XML There are two ways to do so: Using the XElement class or the XDocument class. When you have used this. Read rendered documentation, see the history of any file, and collaborate with contributors on projects across GitHub. There is one row in the table for each column returned in the reader, and the columns of the schema table define properties of the reader’s result set, such as the column name, size, data type and so on. This operator takes a flat sequence of items, organize that sequence into groups (IGrouping[K,V]) based on a specific key and return groups. The content posted here is free for public and is the content of its poster. SortOrder property. Linq group by with multiple where, sum clauses in select causes a timeout. found on the X-Axis) that are used for grouping are actual Measures in the Cube, and the “Days of Week” values (i. The Join and GroupJoin methods are best used indirectly, through the query syntax. Line of business (LOB) applications are mainly driven by CRUD operations on the domain data. Often only a fragment of a string is known to the user, or many of them. An editor's column collection can be defined and customized through Properties. NET? I believe that multiple column Group By on the raw detail data is one of the most important query for reports and user output analysis, because only in the raw detail data you can sum, count and calculate transactional information based on a certain header information. so queryable. com Learn how to use LINQ to group by multiple columns. Table Definition. Factoring WHERE clauses in IQueryable. , metadata, constraints, change tracking, etc. This article explains the topic, How to sum all the values in a column and display it in an external input box in the BatchEditing?. Linq namespace in your using clause. This is known as deferred execution. linq lambda group by multiple. We choose them based on the QuerySource of the tables in the select expression. Created for a screen which needed to hide/show controls based on a radio button list selection, something which I’ve done before but the simplicity of how to implement it with JQuery impressed me so I’m blogging it. Net Framework 4. With over 6,500 students and 1,500+ positive reviews, this course is Udemy's most popular course for learning Entity Framework! Entity Framework is an Object / Relational Mapper (O/RM) that helps you read and write data from and to a database. GroupBy: GroupBy is used to group a sequence into subsets. I'm writing a Function that pulls Records from a DataBase using LINQ to get an IQueryable. LINQ Group By Multiple Columns - Sensible Dev. This tutorial is the third in a series of 12 which teach you how to build MVC 5 applications using Entity Framework for data access and Visual Basic. Linq; namespace AbundantCode { internal class Program { //How to Remove Duplicates and Get […]. Let's try and get all of the rows in a table using Entity Framework. not sure if it will work without it) into the grouped area of the list/tablix/whatever. The given collection would be first sorted based on the first field and then if value of first field would be the same for two elements then it would use second field for sorting and so on. Extended, so that you can call IQueryable. 4 September 2014. This part discusses how to query SQL database with the defined mapping classes. The property that is used to set the layout options that are not inherited from the parent is called columnLayouts. If the query encoded in the object contains grouping/aggregations it gets the detail url associated to the current grouping and to the grouping item model. As you said, you may join multiple tables or select a subset of their columns and return the data in a structure that fits your reports. A is related to B and B is related to C. IEnumerable is inherited by IQueryable, so it has all features of it and of its capabilities. If the condition is in the result of projection (the final select clause), it may be parsed after execution of the SQL, depending on parameter setting selectOperations. SQL has an ability to nest queries within one another. Using Group/By/Into will also give you the best possible performance for those complex queries. using BLToolkit. It's possible to build up dynamic LINQ queries or queries with several conditional criteria. [Entity Framework] Using Include with lambda expressions October 3, 2010 Thomas Levesque 15 Comments I'm currently working on a project that uses Entity Framework 4. I'm working on a LINQ provider so am implementing IQueryable. This part discusses how to query SQL database with the defined mapping classes. What will be the output of query given below. 4 September 2014. Grouping in LINQ with Methods. I also used generics because type of your columns is unknown. A is related to B and B is related to C. LINQ query expressions are similar to SQL SELECT commands with from, where, orderby, group, and select clauses. This article explains the topic, How to sum all the values in a column and display it in an external input box in the BatchEditing?. Peter follows up -- yet again – on a column on how to group results with LINQ using the SQL-like syntax with the same solution using the method-based syntax. Creating PIVOT resultset in SQL Server by RamiVemula · December 12, 2012 PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output, and performs aggregations where they are required on any remaining column values that are wanted in the final output. The following example uses the ToArray method to immediately evaluate the query and convert the sequence into an array. Enumerable class that I find I'm using more and more is the SelectMany( ) method - it wasn't obvious at all to me when I first saw it what it's purpose is. This is the tenth in a series of posts on how to build a LINQ IQueryable provider. you can also write dt. Downloading the LINQ Dynamic Query Library. To update those columns, perform the following steps: 1. Net library in c#, vb. Visual Studio Languages ,. Extending on LINQ. GroupBy(IQueryable, Expression>, Expression>, Expression,TResult>>, IEqualityComparer) Groups the elements of a sequence according to a specified key selector function and creates a result value from each group and its key. For example, to fetch the maximum age in each department on different locations we need to group data on Dept and Location. Let's start by revisiting our IQueryable skeleton implementation. Collections. I would like to pass an IQueryable created from the Entity Framework to a CollectionView and use that to provide the data to the SfDataGrid. Orderby(x=>x. You can refer to the article Querying Related data using Navigational Properties from our last. What is the purpose of the Expression property within this interface? I normally just return something like Expression. Here is an example of how you can use group by multiple columns in linq lambda expression IEnumerable vs IQueryable. EF 6 supports different types of queries which in turn convert into SQL queries for the underlying database. Each column within this collection must be bound to a data source field via the FieldName. GROUP BY can be used in a streaming query as long as one of the grouping expressions is a non-constant monotonic or time-based expression. The in-place searchbox allows you to quickly search for items or documents while staying in the list or library context (in previous versions you were redirected to a search page). The last number i…. Linq group by with multiple where, sum clauses in select causes a timeout. Current version of select2 is 4. 4 September 2014. The DbSet class is derived from IQuerayable. NET MVC Grid. I have two seperate DomainServices, pointing to two different SQL Database Servers. Ok done the first step. order by multiple columns. What will be the output of query given below. Create your first Data Grid using MVCJQGrid First of all in order for you to start write MVCJQGrid coding, you need to add new namespace for the project. You can apply an additional order-by after the group-by to order the groups specificly. Inside this object you can define the child layout objects and their respective options. Today, I was required to order a list of records based on a Name and then ID. The Join and GroupJoin methods are best used indirectly, through the query syntax. Today, I was required to order a list of records based on a Name and then ID. The statement must not reference tables with computed columns. Step 6: Defining Columns. In this sample, a set of words are grouped by the first letter (FirstLetter) of the word and the items in the group are called Words. With over 6,500 students and 1,500+ positive reviews, this course is Udemy's most popular course for learning Entity Framework! Entity Framework is an Object / Relational Mapper (O/RM) that helps you read and write data from and to a database. Improve query performance when selecting almost all rows with many "group by" columns index on all filter/group-by columns and include the aggregate columns. 4 September 2014. Using Grouping instead of Distinct in Entity Framework to Optimize Performance On a number of pages on this web site I display a list of articles. I want to return only one inventory record (an instance of EFModel. This tutorial starts with a general overview of LINQ, and then teaches you how to implement GROUP BY as you would in SQL. Join allows to join multiple sources together based on some join condition:. NET selecting the Key value and the data to place in the group. WhenNotMatched match group could contain only Insert operations. Remote model in contrast is rather declarative to the runtime. Grouping is one of the most powerful capabilities of LINQ. When you have used this. In this tutorial let us look into how to use Join Query in Entity Framework to load the data from two or more tables. For example, to fetch the maximum age in each department on different locations we need to group data on Dept and Location. A keysapce is a Container for column families to group multiple column families, typically one per application. The other answer's snippets are too short and without context. Split Column > By Delimiter parses a text value into two or more columns according to a common character. I want to take this thought a step further, and as implied by the post title, do a group by. Thus far, everything that we've seen has been supported by the C# 3. This article presents a small utility class to sort an "IEnumerable" of objects on multiple fields by the field names provided at the run time using Linq. LINQ GroupBy Explanations and Examples. NET provides is Distinct(). Queries all perform one of three possible tasks: It retrieves an element subset for producing a new sequence without changing individual elements. Extended, so that you can call IQueryable. This operator takes a flat sequence of items, organize that sequence into groups (IGrouping[K,V]) based on a specific key and return groups. To do that you would need to create your own custom implementation of the [Authorize] attribute. Multiple Sorting. like below but. Com and Questpond. Why would you want to do this?. If a grouping column contains a null, that row becomes a group in the result. createquery() retuns new iqueryable<>. Retrieving multiple objects. Using LINQ to SQL for clean and quick Database Access/Interactions. When you have used this. Entity Framework Core provides mechanisms for executing raw SQL queries directly against the database in circumstances where you cannot use LINQ to represent the query (e. Ok done the first step. Note in grid table title, all the label text using the column, button and the message value from the resource file (, in order to realize the multiple languages), pass through the parameFormView object. You will also look at implementing simple. Columnname) in the LINQ query we can easily order data of the source collection. Every architecture principle is created to handle some operational constraints. Sequences in query implement the IQueryable (which in turn derives fromIEnumerable) and after the compilation resolve into query operators from Queryable class – expression trees. Monday - Sunday) are actually based off a single date Dimension. Info: With Join, we provide delegates (lambdas) as arguments. Grouping Results in LINQ. Back to Library DynamicQueryable Class. SELECT Clause. If the LINQ query is executed in. The GroupBy() function (which of course can be used from a LINQ expression as well as from the method syntax and I will show both) provides this functionality. As according to the Project System Documentation (link provided by Jonathan), you can tell based on the formatting of the project file. If a grouping column contains more than one null, the nulls are put into a single group. After some initial hesitation, I have. Both the classes contain the 'Load()' method which accepts a file, a URL or XMLReader and allows XML to be loaded. If you're familiar with traditional SQL JOINs, you are already well equipped for understanding the LINQ JOIN operator. This mechanism also helps prevent local malicious software from running remotely with administrative rights. Group query results. Net Community by providing forums (question-answer) site where people can help each other. You could maintain an extra column for each row containing the time rounded to the hour, and index this column for use in such queries. In the previous article, we manually populated a ListView control through XAML code, but in WPF, it's all about data binding. Defines set exInsertWhenNotMatched takes insert operation options and returns new merge command builder with new operation. This first example shows the Join extension method, and a join query expression. There are three means by which a type can be designed to participate in LINQ queries: implementing IEnumerable<> (or interfaces derived from it), implementing IQueryable<>, or by defining the Query Pattern on the type, with no relationship to these two interfaces. WhenNotMatched match group could contain only Insert operations. You will surely have lots of fun stuff like cartoons, music reviews, movie reviews, puzzles etc. 0 and this is what I came up with; dynamically querying CSV-files. This query might still be faster for a Parquet table than a table with some other file format, but it does not take advantage of the unique strengths. You will also look at implementing simple. Aggregate Functions. Let’s select some existing columns. The reason is: IQueryable has funky implementation of IEnumerable. The statement must not reference tables with computed columns. Columns and Layouts. NET context, you can use IndexOf(), but that method is not supported in LINQ to SQL. However, there is still a large number of operations that C# 3. ; This query can be also be constructed with an implicit AND operation by combining the operator expressions for the price field. Speaker's Night Out. In this post I am going to discuss about comparing the date part of the datetime in linq query. The projected columns in the SELECT statement may not contain aggregate expressions unless the statement uses a GROUP BY expression. By returning an entire object in your query, you will get all of the benefits associated with the entity classes—the most important of which is the ability to keep track of changes to an entity class for database updates. You can apply an additional order-by after the group-by to order the groups specificly. I use this column to keep you. I can sort by any column, except by the range address, when I click on that one, the list is not sorted. Let's say our boss gives us a spreadsheet each week to Do Something Important with in our application. How to group ranged values using SQL Server. 6m developers to have your questions answered on Multiple LINQ Join conditions with differing comparison operators of Data Access, formerly OpenAccess ORM LINQ (LINQ specific questions). I have a table of values like this 978412, 400 978813, 20 978834, 50 981001, 20 As you can see the second number when added to the first is 1 number before the next in the sequence. Using custom grouping operators in LINQ. I have a table that has 100,000+ records, and I don't want to download them all in order to get filtering/sorting/grouping functionality, as that take forever (these rows aren't small), and a waste of bandwidth. Normally while working on a project, I avoid the use of LINQ query and prefer to do all the grouping and ordering operation in the SQL procedure itself but recently, I came across a situation where I need to perform multiple order by operation on a list i. Allow SQL to LINQ conversion in a different language than the model language. Within these Domain Services I have setup some IQueryables in each Domain Service. Basically, GROUP JOIN is like as INNER-EQUIJOIN except that the result sequence is organized into groups. A group that. Querying in Entity Framework. Now we have two options, either we select columns that already exist or define new columns. Today we'll finish up that report while examining SUM(Distinct), and see just how crucial derived tables are when summarizing data from multiple tables. I am trying to group by multiple columns and then sum up the Amount field of all the records into one record. Related Topics. Extended, so that you can call IQueryable. I want to return only one inventory record (an instance of EFModel. NET context, you can use IndexOf(), but that method is not supported in LINQ to SQL. These properties are used by the "from" and "join" statements of the LINQ query. 6m developers to have your questions answered on Multiple LINQ Join conditions with differing comparison operators of Data Access, formerly OpenAccess ORM LINQ (LINQ specific questions). LINQ lets you effortlessly shift part of the query onto the client for processing. I'm writing a Function that pulls Records from a DataBase using LINQ to get an IQueryable. (Why EF Core shipped without GROUP BY support is a separate question. NET Framework component that adds native data querying capabilities to. Also you can use these to return an aggregated value, or in a group-by clause:. One of the cool things I discovered while getting to grips with LINQ is that you can chain LINQ queries together. Join allows to join multiple sources together based on some join condition:. For example, to fetch the maximum age in each department on different locations we need to group data on Dept and Location. If the LINQ query is executed in. All of the examples so far demonstrated selecting the complete set of results or entire table sets. IQueryable queryDemo = from a in orgServiceContext. For example, the search feature in this application allows the user to find all records that meet criteria defined on multiple columns:. Address1_City. GetChildren, this function should return an IQueryable when the item is a node, or an Awe. The list was correct, but they’ve changed everything in 2008. It exists in System. Provides a set of static methods for querying data structures that implement IQueryable. This is known as deferred execution. Linq namespace in your using clause. Sequences in query implement the IQueryable (which in turn derives fromIEnumerable) and after the compilation resolve into query operators from Queryable class – expression trees. As the matter in fact, your IQueryable implementation could be smart enough to track all the things it can't do directly in LDAP (for instance the sorting operations) and send off an LDAP query to AD with the maximum amount of things it can do using LDAP. It's possible to build up dynamic LINQ queries or queries with several conditional criteria. IEnumerable and IQueryable in C# Linq Group Join It is also possible to order based on multiple columns like Employee First and Last Name in ascending order. When using LINQ, it returns IQueryable which is not a collection & hence we can't do group-by or aggregate. In addition, the DataSet also exposes a number of services (i. All of the queries run correctly with FSharpComposableQuery and produce the same answers as the main implementation of F# query. Introduction: Here we will learn how to create or generate QR code in asp. Extending on LINQ. Just write your lambda expression and BOOM!, list sorted. Lazy when it is a lazy node. Column Attribute. CSV is simple two dimensional data format, so we can focus more on what you can do then on the format itself. If you have your own bag of LINQ tricks, please share them in the comments! Also, if you like this article, you may like my next article, Extended LINQ: additional operators for LINQ to objects. Grouping in LINQ with Methods. +1 - Thanks for the comprehensive example. A GroupJoin is in SQL what we call a "Left Outer JOIN" while a Join in SQL refer to "Inner Join". SortOrder property. Let’s select some existing columns. If the query encoded in the object contains grouping/aggregations it gets the detail url associated to the current grouping and to the grouping item model. Also you can use these to return an aggregated value, or in a group-by clause:. Peeps, Im a born again virgin to Silverlight so please bear with me. This mechanism also helps prevent local malicious software from running remotely with administrative rights. There are three means by which a type can be designed to participate in LINQ queries: implementing IEnumerable<> (or interfaces derived from it), implementing IQueryable<>, or by defining the Query Pattern on the type, with no relationship to these two interfaces. Data; using System. net with example or asp. The grouping operators create a group of elements based on the given key. 0 and this is what I came up with; dynamically querying CSV-files. I've just read this interesting article from Anith Sen that lists many different ways to concatenate several row values into a single column (i. -to-anything really) to work. At first look it feels like it is same as T-SQL "Group By" but it is not. Net, LINQ, DataTable, DataSet. ISNULL vs COALESCE - expressions/functions in SQL Server ISNULL & COALESCE with some common features makes them equivalent, but some features makes them work and behave differently, shown below. if want able "see" where() while being added (and manipulate it), must "be" iqueryable<>. LINQ to SQL: GroupBy() One aspect of LINQ I have not covered yet is the equivalent of a GROUP BY in SQL. Calling ToArray also forces immediate execution of the query. My apologies for the delay but I've just pushed the latest code changes, it only works for one column for now, but I'm currently working on it to extend it to multiple columns, this is for testing purposes only until the group paging bug is fixed. If you're familiar with traditional SQL JOINs, you are already well equipped for understanding the LINQ JOIN operator. This article explains the topic, How to sum all the values in a column and display it in an external input box in the BatchEditing?. LINQ is a great tool for C# programmers letting you use familiar syntax with a variety of back-end systems without having to learn another language or paradigm for many query operations. As the matter in fact, your IQueryable implementation could be smart enough to track all the things it can't do directly in LDAP (for instance the sorting operations) and send off an LDAP query to AD with the maximum amount of things it can do using LDAP. A column contains a name, value and timestamp. C# - Chaining LINQ Queries Together Mon 7 Mar 2011. If there are multiple operations within same group - only last one allowed to have no condition. EF 6 supports different types of queries which in turn convert into SQL queries for the underlying database. I would think that a grouping clause or where clause is needed. In the diagram given in below link for each customer I want to select all orders and then for each order I have calculate a TotalPrice = (Sum of all Food Items included in order * Quantity) + ExtraPrice. Use the demo source code to look into the logic of grid sorting and easily implement it in your app. The Datacolumn represents a schema of the column in data table How To Fill Data Into Dataset In VB. A common need within queries is to see if any related entities satisfy a condition:. The in-place searchbox allows you to quickly search for items or documents while staying in the list or library context (in previous versions you were redirected to a search page). LINQ query expressions are similar to SQL SELECT commands with from, where, orderby, group, and select clauses. One of the cool things I discovered while getting to grips with LINQ is that you can chain LINQ queries together. net dynamically generate and display QR code using c#, vb. Group query results. Personally I think this is a good thing. By: After By, we specify the property that will be used to separate groups (here I use Item1, part of the tuples). City into StudentGroup orderby StudentGroup. The fact-checkers, whose work is more and more important for those who prefer facts over lies, police the line between fact and falsehood on a day-to-day basis, and do a great job. Today, my small contribution is to pass along a very good overview that reflects on one of Trump’s favorite overarching falsehoods. Namely: Trump describes an America in which everything was going down the tubes under  Obama, which is why we needed Trump to make America great again. And he claims that this project has come to fruition, with America setting records for prosperity under his leadership and guidance. “Obama bad; Trump good” is pretty much his analysis in all areas and measurement of U.S. activity, especially economically. Even if this were true, it would reflect poorly on Trump’s character, but it has the added problem of being false, a big lie made up of many small ones. Personally, I don’t assume that all economic measurements directly reflect the leadership of whoever occupies the Oval Office, nor am I smart enough to figure out what causes what in the economy. But the idea that presidents get the credit or the blame for the economy during their tenure is a political fact of life. Trump, in his adorable, immodest mendacity, not only claims credit for everything good that happens in the economy, but tells people, literally and specifically, that they have to vote for him even if they hate him, because without his guidance, their 401(k) accounts “will go down the tubes.” That would be offensive even if it were true, but it is utterly false. The stock market has been on a 10-year run of steady gains that began in 2009, the year Barack Obama was inaugurated. But why would anyone care about that? It’s only an unarguable, stubborn fact. Still, speaking of facts, there are so many measurements and indicators of how the economy is doing, that those not committed to an honest investigation can find evidence for whatever they want to believe. Trump and his most committed followers want to believe that everything was terrible under Barack Obama and great under Trump. That’s baloney. Anyone who believes that believes something false. And a series of charts and graphs published Monday in the Washington Post and explained by Economics Correspondent Heather Long provides the data that tells the tale. The details are complicated. Click through to the link above and you’ll learn much. But the overview is pretty simply this: The U.S. economy had a major meltdown in the last year of the George W. Bush presidency. Again, I’m not smart enough to know how much of this was Bush’s “fault.” But he had been in office for six years when the trouble started. So, if it’s ever reasonable to hold a president accountable for the performance of the economy, the timeline is bad for Bush. GDP growth went negative. Job growth fell sharply and then went negative. Median household income shrank. The Dow Jones Industrial Average dropped by more than 5,000 points! U.S. manufacturing output plunged, as did average home values, as did average hourly wages, as did measures of consumer confidence and most other indicators of economic health. (Backup for that is contained in the Post piece I linked to above.) Barack Obama inherited that mess of falling numbers, which continued during his first year in office, 2009, as he put in place policies designed to turn it around. By 2010, Obama’s second year, pretty much all of the negative numbers had turned positive. By the time Obama was up for reelection in 2012, all of them were headed in the right direction, which is certainly among the reasons voters gave him a second term by a solid (not landslide) margin. Basically, all of those good numbers continued throughout the second Obama term. The U.S. GDP, probably the single best measure of how the economy is doing, grew by 2.9 percent in 2015, which was Obama’s seventh year in office and was the best GDP growth number since before the crash of the late Bush years. GDP growth slowed to 1.6 percent in 2016, which may have been among the indicators that supported Trump’s campaign-year argument that everything was going to hell and only he could fix it. During the first year of Trump, GDP growth grew to 2.4 percent, which is decent but not great and anyway, a reasonable person would acknowledge that — to the degree that economic performance is to the credit or blame of the president — the performance in the first year of a new president is a mixture of the old and new policies. In Trump’s second year, 2018, the GDP grew 2.9 percent, equaling Obama’s best year, and so far in 2019, the growth rate has fallen to 2.1 percent, a mediocre number and a decline for which Trump presumably accepts no responsibility and blames either Nancy Pelosi, Ilhan Omar or, if he can swing it, Barack Obama. I suppose it’s natural for a president to want to take credit for everything good that happens on his (or someday her) watch, but not the blame for anything bad. Trump is more blatant about this than most. If we judge by his bad but remarkably steady approval ratings (today, according to the average maintained by 538.com, it’s 41.9 approval/ 53.7 disapproval) the pretty-good economy is not winning him new supporters, nor is his constant exaggeration of his accomplishments costing him many old ones). I already offered it above, but the full Washington Post workup of these numbers, and commentary/explanation by economics correspondent Heather Long, are here. On a related matter, if you care about what used to be called fiscal conservatism, which is the belief that federal debt and deficit matter, here’s a New York Times analysis, based on Congressional Budget Office data, suggesting that the annual budget deficit (that’s the amount the government borrows every year reflecting that amount by which federal spending exceeds revenues) which fell steadily during the Obama years, from a peak of $1.4 trillion at the beginning of the Obama administration, to $585 billion in 2016 (Obama’s last year in office), will be back up to $960 billion this fiscal year, and back over $1 trillion in 2020. (Here’s the New York Times piece detailing those numbers.) Trump is currently floating various tax cuts for the rich and the poor that will presumably worsen those projections, if passed. As the Times piece reported: