Thursday, March 31, 2011

C#: I want to pass messages like a file path to my forms application like a console application, how would I do that?

C#: I want to pass messages like a file path to my forms application like a console application, how would I do that?

I was told I needed to find my main method to add string[] args, but I wouldn't know which one that would be in Windows Forms. Which would my main method be in C# windows forms application?

From stackoverflow
  • If you want to get access to the command line parameters, use Environment.CommandLine

    string args = Environment.CommandLine;
    

    You can do this whether or not you have a main method with string[] args in your code.

  • There's one Main(), which is inside Program.cs. But in WinForms app Environment.GetCommandLineArgs() will be a better option.

  • in your public constructor, use the following:

    string[] args = Environment.GetCommandLineArgs();

    this will give you a string array of the arguments.

  • Ok, string[] args = Environment.GetCommandLineArgs() is a better option. But I will keep the following answer as an alternative to it.

    Look for a file called Program.cs containing the following code fragment...

    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
    

    and change that to

    static class Program
    {
    
        public static string[] CommandLineArgs { get; private set;}
    
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            CommandLineArgs = args;
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
    

    Then access the command line args from your form ...

    Program.CommandLineArgs
    
  • Your Main() method is located in Program.cs file, typically like this:

    [STAThread]
    static void Main()
    {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new Form1());
    }
    

    You should modify the Main() to the following:

    static void Main(string[] args)
    

    You'll have access to the arguments passed.

    Also, you could access the arguments using Environment.GetCommandLineArgs()

  • hey guise when i do so with my application i get the following string "D:\MyData~1\MyMain~1.pfb" and it supposed to be like that "D:\My Data\My Main Phone Book.pbf" and i don't know why pls any bodyhas asolution to this

    Matt Ellen : Hi falcon eyes, you need to ask this as a separate question - i.e. as its own question. be sure to give an example of the code you're running and the output you're getting.

Bugzilla: Set permissions to make a product readonly for all users.

Hi,

i am using a single instance of Bugzilla for issue tracking in multiple projects. Some of my projects are restricted to be visible only to a single group of people while other projects have to be ready-only for everybody (even if they do not have a user account in bugzilla). Submitting bugs should always only be possible for authenticated users. Editing bugs is also restricted only to a small group of people and the bug reporter himself.

Does somebody know how i have to set permissions in bugzilla if i want to make a single project read-only for all users (without logging in)? At the moment you can only view bugs if you have logged in.

Update As sereda described "requirelogin" is turned "off". I also have a group corresponding to each product.

For each product i have set the group access to: ProductXY: Mandatory/Mandatory, ENTRY

User are added to the groups by Regex (".*" for all users) in the group properties.

But when i try to open a bug as anonymous user bugzilla says "You are not authorized to access bug #8. To see this bug, you must first log in to an account with the appropriate permissions."

From stackoverflow
  • You can make all projects readable anonymously by default by setting "requirelogin" to off in Adminitration | Parameters | User Authentication. Then you would need to check if those products that you don't want to be publicly visible have correct group security (I think it should be mandatory/mandatory setting for a group corresponding to each product).

    Update

    I believe that for a bug to be visible to an anonymous user, it must not belong to any group. Since all your products have 'mandatory' settings, all product bugs belong to corresponding product group, and so not ever visible to anonymous.

    I'd suggest to change group controls for public products to "Shown/NA", and then mass update all bugs and remove them from all groups.

    Alexander : Updated my original post. Seems like it has to be another permission.

PHP and outputting one-to-many results

I've only dealt with one-to-one relationships in php so far, but I'm stuck on a problem which involves a one-to-many relationship. I've been sitting on this for a few days with no luck, so I'm desperate for someone to step in and show me a solution before I lose my mind.

In my database have a series of urls, which are received by a SELECT query along with various other fields, from different tables. Every url has at least one category associated with it, but can have multiple categories. So in my results I might see something that looks a bit like this:

link_id = 3   url= 'http://www.somesite1.com'   category = 'uncategorised'
link_id = 4   url= 'http://www.somesite2.com'   category = 'travel'
link_id = 4   url= 'http://www.somesite2.com'   category = 'fun'
link_id = 4   url= 'http://www.somesite2.com'   category = 'misc'
link_id = 3   url= 'http://www.somesite3.com'   category = 'uncategorised'

I have got this to work, kind of. When I loop through and print them off, using a while loop and mysql fetch array, the result looks exactly like it does above. Thats great, except what I need is for it to read something like:

link_id = 4   url = 'http://www.somesite2.com'   category = 'travel fun misc'

So that basically all of the categories for each url get combined somehow, as they are printed out. My first attempt led me to try a nested while loop, but it didn't work and i'm not sure if this is feasible. Apart from that I'm wondering if I might need a multidimensional array (complete guess, i've never had to use one before).

I'm ordering these results by link id as above, so I know if the link id in the current loop iteration, matches the one in the last iteration - then I have something which has more than one category.. I think I'm really close, but I just can't figure it out.

Any ideas?

From stackoverflow
  • You should be using a connection table.

    1st you have a table of links

    id = 1 url = something
    id = 2 url = something else
    

    Then you have a table of categories

    id = 1 category = something
    id = 2 category = something else
    

    Then you have a connection table

    url_id = 1 category_id = 1
    url_id = 1 category_id = 2
    url_id = 2 category_id = 1
    

    This should atleast get you started.

    Jon : ahh sorry, I should have made it a bit more clear. If I understand correctly, I do have a set up like this. A table called categories, just being a repository of all the categories that exist, then a table that just contains urls, then a table with url_id's and cat_id's to join them together.
    Ólafur Waage : No problem :) I'll keep the answer until you update the question if you want to do that.
  • use an array keyed on the id and url iterate through the values and add to it as follows:

    $link_categories[ $id ] .= $category." ";
    
    $result = mysql_query("SElECT * FROM LINKS");
    
    $link_categories = array();
    
    while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
    {
        if (!isset($link_categories[$row['link']]))
            $link_categories[$row['link']] = " ";
        else
            $link_categories[$row['link']] .= " ";
    
        $link_categories[$row['link']] .= $row['category'];
    }
    
    print_r($link_categories);
    

    Results in:

    Array
    (
        [http://a.com] =>  test evaluate performance
        [http://b.com] =>  classify reduce
        [http://c.com] =>  allocate
    )
    

    This isn't the 'right' way of doing this - really the relationships should be defined in a seperate table with a 1-many relationship.

  • you need to use a control break algorithm.

    set last_link variable to null
    set combined_category to null
    exec query
    
    loop over result set {
        if last_link == null {
            last_link=fetch_link
        }
        if fetch_link==last_link {
            set combined_category+=ltrim(' '.fetch_category)
        } else {
            display html for last_link and combined_category
            set last_link=fetch_link
            set combined_category=fetch_category
        }
    }//loop
    
    display html for last_link and combined_category
    

    I used "display html" as a generic "work" event, you could push this out to a array structure, etc. instead...

  • There is also the "GROUP_CONCAT" function in mysql. That should do exactly what you want to achieve.

    Something like :

    SELECT url, GROUP_CONCAT(category) AS categories FROM yourtable GROUP BY url
    
    Jon : This worked perfectly when I ran the query, and again when I plugged it into my php script. I wasn't aware of that function, but it was exactly what I was after. Thanks!

Grouping data with Linq or not possibe?

I have a List of concrete objects. Some require to be analyzed to take a decision to which one will be kept (when the group contain more than 1 occurence).

Here is a simplified example:

 List<MyObject> arrayObject = new List<MyObject>();
 arrayObject.Add(new MyObject { Id = 1, Name = "Test1", Category = "Cat1"});
 arrayObject.Add(new MyObject { Id = 2, Name = "Test2", Category = "Cat2" });
 arrayObject.Add(new MyObject { Id = 2, Name = "Test2", Category = "Cat3" });

This will required to be at the end of the analyze only :

 arrayObject.Add(new MyObject { Id = 1, Name = "Test1", Category = "Cat1"});
 arrayObject.Add(new MyObject { Id = 2, Name = "Test2", Category = "Cat3" });

As you see the Id2 with Cat2 is gone because the business logic took it off. So what should be done is to be able to get those who have more than 1 category and to apply a logic on it.

Here is what I have so far :

        List<MyObject> arrayObject = new List<MyObject>();
        arrayObject.Add(new MyObject { Id = 1, Name = "Test1", Category = "Cat1"});
        arrayObject.Add(new MyObject { Id = 2, Name = "Test2", Category = "Cat2" });
        arrayObject.Add(new MyObject { Id = 2, Name = "Test2", Category = "Cat3" });


        var filtered = from arrayObject1 in arrayObject
                        group arrayObject by new { arrayObject1.Id, arrayObject1.Name }
                        into g
                        select new { KKey = g.Key, Obj = g };


        foreach(var c in filtered)
        {
            Console.WriteLine(c.KKey + ":" + c.Obj.Count());
            foreach (var cc in c.Obj)
            {
                //Put some Business Logic here to get only 1... but to simplify will just print
                Console.WriteLine("--->" + cc);
            }
        }

The problem is 1) cc is not of type MyObject, second, I have to get all properties in the group by new... I might have few objects that will be different.

Is it possible with Linq? Cause, I can do it without using Linq... but I am trying to apply new stuff of this framework (3.5) as much as I can. Thank

From stackoverflow
  • The problem is in the line that says:

    group arrayObject by
    

    It should say:

    group arrayObject1 by
    
    Daok : Oh my! Not it works. Do you have an idea that will let me not have to add all field in the group arrayObject1 by new { arrayObject1.Id, arrayObject1.Name }. In fact the real object has several property. Isn't there a way to group by "all field except x"?

C to Python via SWIG: can't get void** parameters to hold their value

I have a C interface that looks like this (simplified):

extern bool Operation(void ** ppData);
extern float GetFieldValue(void* pData);
extern void Cleanup(p);

which is used as follows:

void * p = NULL;
float theAnswer = 0.0f;
if (Operation(&p))
{
   theAnswer = GetFieldValue(p);
   Cleanup(p);
}

You'll note that Operation() allocates the buffer p, that GetFieldValue queries p, and that Cleanup frees p. I don't have any control over the C interface -- that code is widely used elsewhere.

I'd like to call this code from Python via SWIG, but I was unable to find any good examples of how to pass a pointer to a pointer -- and retrieve its value.

I think the correct way to do this is by use of typemaps, so I defined an interface that would automatically dereference p for me on the C side:

%typemap(in) void** {
   $1 = (void**)&($input);
}

However, I was unable to get the following python code to work:

import test
p = None
theAnswer = 0.0f
if test.Operation(p):
   theAnswer = test.GetFieldValue(p)
   test.Cleanup(p)

After calling test.Operation(), p always kept its initial value of None.

Any help with figuring out the correct way to do this in SWIG would be much appreciated. Otherwise, I'm likely to just write a C++ wrapper around the C code that stops Python from having to deal with the pointer. And then wrap that wrapper with SWIG. Somebody stop me!

Edit:

Thanks to Jorenko, I now have the following SWIG interface:

% module Test 
%typemap (in,numinputs=0) void** (void *temp)
{
    $1 = &temp;
}

%typemap (argout) void**
{
    PyObject *obj = PyCObject_FromVoidPtr(*$1, Cleanup);
    $result = PyTuple_Pack(2, $result, obj);
}
%{
extern bool Operation(void ** ppData); 
extern float GetFieldValue(void *p); 
extern void Cleanup(void *p);
%} 
%inline 
%{ 
    float gfv(void *p){ return GetFieldValue(p);} 
%} 

%typemap (in) void*
{
    if (PyCObject_Check($input))
    {
        $1 = PyCObject_AsVoidPtr($input);
    }
}

The python code that uses this SWIG interface is as follows:

import test 
success, p = test.Operation()
if success:
   f = test.GetFieldValue(p) # This doesn't work 
   f = test.gvp(p) # This works! 
   test.Cleanup(p)

Oddly, in the python code, test.GetFieldValue(p) returns gibberish, but test.gfv(p) returns the correct value. I've inserting debugging code into the typemap for void*, and both have the same value of p! The call Any ideas about that?

From stackoverflow
  • Would you be willing to use ctypes? Here is sample code that should work (although it is untested):

    from ctypes import *
    
    test = cdll("mydll")
    
    test.Operation.restype = c_bool
    test.Operation.argtypes = [POINTER(c_void_p)]
    
    test.GetFieldValue.restype = c_float
    test.GetFieldValue.argtypes = [c_void_p]
    
    test.Cleanup.restype = None
    test.Cleanup.argtypes = [c_void_p]
    
    if __name__ == "__main__":
        p = c_void_p()
        if test.Operation(byref(p)):
            theAnswer = test.GetFieldValue(p)
            test.Cleanup(p)
    
    Jason Sundram : Thanks -- I'd prefer to use SWIG if I can, but if it doesn't work out, I may consider ctypes.
  • I agree with theller, you should use ctypes instead. It's always easier than thinking about typemaps.

    But, if you're dead set on using swig, what you need to do is make a typemap for void** that RETURNS the newly allocated void*:

    %typemap (in,numinputs=0) void** (void *temp)
    {
        $1 = &temp;
    }
    
    %typemap (argout) void**
    {
        PyObject *obj = PyCObject_FromVoidPtr(*$1);
        $result = PyTuple_Pack(2, $result, obj);
    }
    

    Then your python looks like:

    import test
    success, p = test.Operation()
    theAnswer = 0.0f
    if success:
       theAnswer = test.GetFieldValue(p)
       test.Cleanup(p)
    

    Edit:

    I'd expect swig to handle a simple by-value void* arg gracefully on its own, but just in case, here's swig code to wrap the void* for GetFieldValue() and Cleanup():

    %typemap (in) void*
    {
        $1 = PyCObject_AsVoidPtr($input);
    }
    
    Jason Sundram : Thanks for the swig. test.Operation() now works, but I'm having trouble calling test.GetFieldValue(p) from the python code. Do I need a typemap for void* as well?
    Jorenko : Weird. I added a typemap for that to my answer, just in case, though I haven't had a chance to test it...
    Jason Sundram : Thanks -- so this is a bit weird. Without the typemap, GetFieldValue claims that p is null. With the typemap, there are no complaints, but I get back a garbage value in theAnswer.
    Jorenko : Well, keep in mind that the typemaps are actual C snippets that get inserted before/after the wrapped function call. If you like you can put debug prints, etc there to try to work out what the problem is.
    Jason Sundram : Thanks -- Here's the interface (+ your stuff): % module Test %{ extern float GetFieldValue(void *p); }% %inline %{ float gfv(void *p){ return GetFieldValue(p);} %} Oddly, test.GetFieldValue(p) returns gibberish, but test.gfv(p) returns the correct value. But both have the same value of p!
    Jason Sundram : Sorry that last comment was really hard to read -- I've updated the question so the interface code is readable.
    Jorenko : How are you calling gvf()?
    Jason Sundram : I've updated the question with the calling code (at the bottom). Basically, I'm calling gvf and GetFieldValue() the same way.

Web-Developer's Project Template Directory

IMPORTANT: The accepted answer was accepted post-bounty, not necessarily because I felt it was the best answer.


I find myself doing things over and over when starting new projects. I create a folder, with sub-folders and then copy over some standard items like a css reset file, famfamfam icons, jquery, etc.

This got me thinking what the ideal starting template would be. The reason I'm asking is that I'm going through once again and am wondering what I should include in my template so that I don't have to go back in the future and do this all over again with every new site I start.

What I currently have follows:

Project Template Folder
  • index.html -- XHTML 1.0 Strict Doctype. Meta Tags. CSS/js Files Referenced.
  • css/
    • default.css -- Empty. Reserved for user-styles.
    • 960/ -- 960 Grid System for CSS Layouts.
      • 960.css
      • reset.css
      • text.css
  • js/
    • default.js -- Empty. Reserved for user-scripts.
    • jQuery/ -- Light-Weight Javascript Framework
      • jquery-1.3.1.min.js
  • img/
    • famfamfam/ -- Excellent collection of png icons
      • icons/
        • accept.png
        • add.png
        • ...etc
From stackoverflow
  • I have a similar structure and naming convention but for CSS, I use BluePrint which I find is more extensible. Also prefer jQuery having recently switched from prototype. In addition I have a common.js file that is an extension with custom functions for jQuery.

    A /db/ folder with .sql files containing schema definitions. A /lib/ folder for common middle-tier libraries.

    I will also have a /src/ folder which will sometimes have raw files such as Photoshop templates, readme's, todo lists etc.

    Jonathan Sampson : Excellent idea regarding Photoshop files. I work a lot in PS and usually do have .PSD's littering my desktop from time to time, or littering my project folder.
  • I think the structure is good. The addition of a few other folders depends on what type of work you are completing.

    For freelancing and the like, the addition of PSD folders, client comments would be a nice addition.

  • A very MS skewed view, but my SOP right now is along the lines of:

    • documentation/
      • architecture/ (what you might call code documentation)
      • communications/ (important client docs)
      • spec/
      • whitepapers/
    • graphics/
      • *.psd
    • source/

      • com.mycompany.projectname.solutionA/
      • com.mycompany.projectname.solutionB/
      • com.mycompany.projectname.solutionC/
      • com.mycompany.projectname.solutionX/ (project in the business sense here)

        • businesslogic/
          • *.cs (or whatever)
        • (further projects - in the visual studio sense)
        • site/

          • handlers/ (rarely do I use actual .html these days)
          • modules/
          • resources/

            • img/ (pngs jpegs, gifs whatever)

              • skin/
                • icons/
                • backgrounds/
            • js/ (compressed when published)

              • library/ (standard code)
              • common/ (app specific code)
              • *.js (app specific code, hopefully nil)
            • css/
              • skinX/ (even if there is only "default")
                • extension.css
              • base.css
            • transforms/(always hidden from public by config or build process)
              • *.xslt
        • unittests/
          • mocks/
          • testmain.cs (or whatever)
    • thirdparty/
      • dependencies
  • If you have a lot of projects with a lot of static content in common (e.g. jquery, css framework, etc) make yourself a media server to serve all these. Then, instead of creating a bunch of folder structure from a "template" all you do is include the right files in your project's html. If you really want a template, your template becomes one html file instead of a directory structure.

    This also gives you an easy way to update the static media for your sites (e.g. moving to the next version of 960). you only have to do it in one place. Of course, you still have to make sure that your updates don't break existing sites! :)

    You can make the scheme a bit more complicated if certain projects have overlapping needs but are different from others. Just have a directory at the top level of the server for each setup and to each setup corresponds one html "template". The main idea is to have to deal with only one copy of everything that is common.

    You can certainly do this on a small VM (e.g. linode) for $20/mo or a virtual web-server on your current web server. You don't really need a server, for that matter, you just need a folder. However, I think you can have some significant performance gains by having a dedicated media servers. I'd recommend using a fine-tuned apache or nginx for this purpose.

    As for site-specific static files, it is also a good idea that they live on the media server and the directory structure would probably be exactly what you have, but they would/should be empty directories.

  • I definitely love the idea of having a skeleton template folder like this, but if you use a few different technologies, definitely pay close attention to the structure. My VB.net folder structure has a totally different setup compared to PHP. It sounds like common sense, but I have seen people approach both the same way.

  • My web development framework sits in a git repository. Common code, such as general purpose PHP classes gets developed in the master branch. All work for a particular website gets done on a branch, and then changes that will help in future work get merged back into master.

    This approach works well for me because I have full revision control of all the websites, and if I happen to fix a bug or implement a new feature while working on a branch I can do the merge, and then everything benefits.

    Here's what my template looks like:

    /
    |-.htaccess            //mod_rewrite skeleton
    |-admin/               //custom admin frontend to the CMS
    |-classes/             //common PHP classes
    |-dwoo/                //template system
    |-config/              //configuration files (database, etc)
    |-controllers/         //PHP scripts that handle particular URLs
    |-javascript/
          |-tinyMCE/
          |-jquery/
    |-modules              //these are modules for our custom CMS
          |-news/
          |-mailing_list/
          |-others
    |-private/             //this contains files that won't be uploaded (.fla, .psd, etc)
          |-.htaccess      //just in case it gets uploaded, deny all
    |-templates/           //template source files for dwoo
    
    Thelema : This is a bit heavyweight a solution, I think. Having all websites I've developed in one git tree, and just different branches... I guess if your projects have so much in common, it'd update them all on a utility bugfix.
    MichaelM : The reason I am doing it like that is we have an in house developed CMS that all the sites use, that makes up the majority of the codebase. A more elegant solution would be to have the CMS in its own repo and use git-submodule to clone it into each website's own repo. This will be done eventually ;)
  • At work we use Code Igniter as a PHP framework for our web applications and have created a new project template which does exactly that: Simple directory structure, Blueprint CSS, jQuery and the Code Igniter application folder, filled with a couple of commonly used libraries (Authentication, some speciales models for often used databases...).

    The main motto here is: It's always easier to delete components than to add them. So fill your template up.

    (And when I'm starting a new project in my spare time I sorely miss that template...)

  • I think what you have here is great.... What you've listed is of course all about the public front end of your app. My only addition to this, is to keep all your backend code and source out of the public web space if possible, as the less things you have in the public space, the more secure your app is.

    So I'd suggest you take your entire tree, and put it in:

    httpdocs/(all you had in your project template folder)
    

    then put all your backend code (e.g. php libraries, sql files, etc) in adjacent subdirectories:

    httpdocs/(all you had in your project template folder)
    phplibs/
    sql/
    

    etc.

    And, even for your front end stuff, make sure you don't copy in any example files that may come with your front end libraries, as the examples themselves may have security problems that would allow people to XSS or otherwise compromise your site.

  • I have been using the following setup for a while now with great results:

    • /site: This is where my actual working website will live. I'll install my CMS or platform in this directory after the templates are created.
      • .htaccess (basic tweaks I usually find myself enabling anyway)
      • robots.txt (so I don't forget to disallow items like /admin later)
    • /source: Contains any comps, notes, documents, specifications, etc.

    • /templates: Start here! Create all static templates that will eventually need to be ported into the CMS or framework of /site.

      • /behavior
        • global.js (site-specific code; may be broken out into multiple files as needed)
      • /media: Images, downloadable files, etc. Organized as necessary

      • /style: I prefer modular CSS development so I normally end up with many stylesheet for each unique section of the website. This is cleaned up greatly with Blender - I highly recommend this tool!

        • behavior.css (any styling that requires a JS-enabled browser)
        • print.css (this eventually gets blended, so use @media print)
        • reset.css (Eric Meyer's)
        • screen.css (for @media screen, handheld)
      • /vendor: all 3rd party code (jQuery, shadowbox, etc.)

      • Blendfile.yaml (for Blender; see above)

      • template.html (basic starting template; can be copied and renamed for each unique template)
  • I use a similar layout, but with one major exception: all of these directories live under a top-level media/ directory. This is for a few reasons:

    1. This directory is rsync'd to two other servers which handle all of the static media requests.
    2. Having multiple hosts allows some browsers to make more parallel requests for support files.
    3. The media/ directory has its own .htaccess file which strips off a psuedo directory from the path which is the date-time last modified of the image (or whatever).

    A custom template tag (I have used this with 2 Django projects, but you could do it in PHP, etc.) generates urls which a) semi-randomly choose one of the media servers, b) add the time-based pseudo directory to the path, and c) give the object an Expires time of now + 10 years.

  • I like OPs as a default start point. your standard template should err on simplicity, with the ability to add complexity only if it's needed.

    one addition:

    /robots.txt

selecting top column1 with matching column2

sorry for asking this, but i'm runnin' out of ideas

i have this table:

[id]    [pid]    [vid]
1        4        6844
1        5        6743
2        3        855
2        6        888
...

how to i query this eg.table to get the following result:

[id]    [pid]    [vid]
1        5        6743
2        6        888

i want to get the highest [pid] for an [id] with the [vid] matching to this [pid]

any ideas?

i'm using mssql 2008

From stackoverflow
  • one way

    select t1.* from
    (select id,max(pid) as Maxpid
    from yourtable
    group by id) t2
    join yourtable t1 on t2.id = t1.id
    and t2.Maxpid = t1.pid
    
    Andreas Niedermair : sorry for depriving you the points :) but Bliek's solution is much more comfortable and offers a lot more of options...
  • Since you're using Microsoft SQL Server 2008, then I'd recommend Common Table Expressions and the OVER clause to accomplish dividing the results into groups by id, and returning just the top row in each group (ordered by pid). Bliek's answer shows one way to do that.

    (This same basic approach, by the way, is very useful for more efficient paging, as well.)

    There isn't a fantastically great way to do this with "standard" SQL. The method show in SQLMenace's answer will only work in databases where you can use a subquery as a table. It'd be one way to accomplish this in SQL Server 2000, for example, but may not work in every mainstream RDBMS.

    Andreas Niedermair : sry ... it's mssql 2008
  • I would use Common Table Expressions (CTE). This offers lots of possibilities like so:

    WITH Result (RowNumber, [id], [pid], [vid])
    AS
    (
        SELECT Row_Number() OVER (PARTITION BY [id]
                                  ORDER     BY [vid] DESC)
              ,[id]
              ,[pid]
              ,[vid]
          FROM MyTable
    )
    SELECT [id]
          ,[pid]
          ,[vid]
      FROM Result
     WHERE RowNumber = 1
    
    Andreas Niedermair : as your solution provides more options, i'll give you the point!